TestGoalUpdate.setup()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 3
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 3
dl 3
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
import pytest
2
from django.urls import reverse
3
from rest_framework import status
4
5
from goals.models import Category, Board, BoardParticipant, Goal
6
from tests.utils import BaseTestCase
7
8
9
@pytest.fixture()
10
def another_user(user_factory):
11
    return user_factory.create()
12
13
14 View Code Duplication
@pytest.mark.django_db()
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
15
class GoalTestCase(BaseTestCase):
16
17
    @pytest.fixture(autouse=True)
18
    def set_url(self, board_factory, category_factory, goal_factory, user):
19
        self.board: Board = board_factory.create(with_owner=user)
20
        self.category: Category = category_factory.create(board=self.board)
21
        self.goal: Goal = goal_factory.create(category=self.category)
22
        self.url = reverse('goals:goal-detail', args=[self.goal.id])
23
24
    def test_auth_required(self, client):
25
        """Тест на endpoint [GET, PATCH, DELETE]: /goals/goal/<id>
26
27
        Производит проверку требований аутентификации.
28
        """
29
        response = getattr(client, self.method)(self.url, {})
30
        assert response.status_code == status.HTTP_403_FORBIDDEN
31
32
    def test_user_not_board_participant(self, client, another_user):
33
        """Тест на endpoint [GET, PATCH, DELETE]: /goals/goal/<id>
34
35
        Производит проверку отображения цели только категории доски,
36
        в которой пользователь является участником
37
        """
38
        assert not self.board.participants.filter(user=another_user).count()
39
40
        client.force_login(another_user)
41
        response = getattr(client, self.method)(self.url)
42
        assert response.status_code == status.HTTP_404_NOT_FOUND
43
44
45 View Code Duplication
class TestGoalRetrieve(GoalTestCase):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
46
    method = 'get'
47
48
    def test_success(self, auth_client, user):
49
        """Тест на endpoint GET: /goals/goal/<id>
50
51
        Производит проверку корректности структуры ответа при успешном запросе цели.
52
        """
53
        response = auth_client.get(self.url)
54
        assert response.status_code == status.HTTP_200_OK
55
56
        assert self.board.participants.count() == 1
57
        participant: BoardParticipant = self.board.participants.last()
58
        assert participant.user == user
59
60
        assert response.json() == {
61
            "id": self.goal.id,
62
            "user": {
63
                "id": self.goal.user.id,
64
                "username": self.goal.user.username,
65
                "first_name": self.goal.user.first_name,
66
                "last_name": self.goal.user.last_name,
67
                "email": self.goal.user.email
68
            },
69
            "created": self.datetime_to_str(self.goal.created),
70
            "updated": self.datetime_to_str(self.goal.updated),
71
            "title": self.goal.title,
72
            "description": self.goal.description,
73
            "status": 1,
74
            "priority": 2,
75
            "due_date": None,
76
            "category": self.category.id
77
        }
78
79
80 View Code Duplication
class TestGoalUpdate(GoalTestCase):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
81
    method = 'patch'
82
83
    @pytest.fixture(autouse=True)
84
    def setup(self):
85
        self.participant: BoardParticipant = self.category.board.participants.last()
86
87
    def test_failed_update_goal_by_reader(self, faker, auth_client):
88
        """Тест на endpoint PATCH: /goals/goal/<id>
89
90
        Производит проверку отсутствия у пользователя возможности редактировать цель в категории доски,
91
        где он является читателем.
92
        """
93
        self.participant.role = BoardParticipant.Role.reader
94
        self.participant.save(update_fields=('role',))
95
        assert self.participant.role == BoardParticipant.Role.reader
96
97
        response = auth_client.patch(self.url, data={
98
            'title': faker.sentence(),
99
            'category': self.category.id
100
        })
101
        assert response.status_code == status.HTTP_403_FORBIDDEN
102
103
    @pytest.mark.parametrize(
104
        'user_role',
105
        [BoardParticipant.Role.owner, BoardParticipant.Role.writer],
106
        ids=['owner', 'writer']
107
    )
108
    def test_success_update_goal_by_owner_or_writer(self, auth_client, faker, user_role):
109
        """Тест на endpoint PATCH: /goals/goal/<id>
110
111
        Производит проверку наличия у пользователя возможности редактировать цель в категории доски,
112
        где он является автором или редактором.
113
        """
114
        self.participant.role = user_role
115
        self.participant.save(update_fields=('role',))
116
        assert self.participant.role == user_role
117
118
        new_title = faker.sentence()
119
120
        response = auth_client.patch(self.url, {'title': new_title})
121
        assert response.status_code == status.HTTP_200_OK
122
123
        self.goal.refresh_from_db(fields=('title',))
124
        assert self.goal.title == new_title
125
126
127
class TestGoalDestroy(GoalTestCase):
128
    method = 'delete'
129
130
    @pytest.fixture(autouse=True)
131
    def setup(self):
132
        self.participant: BoardParticipant = self.board.participants.last()
133
134
    def test_failed_delete_goal_by_reader(self, auth_client):
135
        """Тест на endpoint DELETE: /goals/goal/<id>
136
137
        Производит проверку отсутствия у пользователя возможности удалить цель в категории доски,
138
        где он является читателем.
139
        """
140
        self.participant.role = BoardParticipant.Role.reader
141
        self.participant.save(update_fields=('role',))
142
        assert self.participant.role == BoardParticipant.Role.reader
143
144
        response = auth_client.delete(self.url)
145
        assert response.status_code == status.HTTP_403_FORBIDDEN
146
147
    @pytest.mark.parametrize(
148
        'user_role',
149
        [BoardParticipant.Role.owner, BoardParticipant.Role.writer],
150
        ids=['owner', 'writer']
151
    )
152
    def test_success_delete_goal_by_owner_or_writer(self, auth_client, user_role):
153
        """Тест на endpoint DELETE: /goals/goal/<id>
154
155
        Производит проверку наличия у пользователя возможности удалить цель в категории доски,
156
        где он является автором или редактором. А так же выполнение следующего условия:
157
            - цель: Status == archived
158
        """
159
        self.participant.role = user_role
160
        self.participant.save(update_fields=('role',))
161
        assert self.participant.role == user_role
162
163
        response = auth_client.delete(self.url)
164
        assert response.status_code == status.HTTP_204_NO_CONTENT
165
166
        self.goal.refresh_from_db(fields=('status',))
167
        assert self.goal.status == Goal.Status.archived
168