Fakultas Ilmu Komputer UI

tests.py 14.3 KB
Newer Older
1
2
3
import json
from django.test import TestCase
from django.contrib.auth.models import Group
4
from django.core.files.uploadedfile import SimpleUploadedFile
5
6
7
8
9
from rest_framework.test import APITestCase, APIClient
from rest_framework import status
from dietela_quiz.models import DietProfile
from authentication.models import CustomUser
from nutritionists.models import Nutritionist
10
from diet_questionnaire.models import DietQuestionnaire
11
12
from authentication.serializers import CustomUserDetailsSerializer
from django.db.models import Q
13
14
from .models import DietRecommendation

15

16
class GetProfilesAndCSVTest(APITestCase):
17
18
19
20
21
    client = APIClient()
    @classmethod
    def setUpTestData(cls):
        cls.BASE_URL = "/profiles/"

22
        cls.diet_profile_1 = DietProfile.objects.create(
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
            name="test",
            email="test@test.com",
            age=20,
            weight=61,
            height=172,
            gender=2,
            special_condition=1,
            body_activity=1,
            vegetables_in_one_day=1,
            fruits_in_one_day=1,
            fried_food_in_one_day=1,
            sweet_snacks_in_one_day=1,
            sweet_drinks_in_one_day=1,
            packaged_food_in_one_day=1,
            large_meal_in_one_day=1,
            snacks_in_one_day=1,
            breakfast_type=1,
            current_condition=1,
            problem_to_solve=1,
            health_problem=[2, 3])

44
45
        cls.diet_profile_2 = DietProfile.objects.create(
            name="test2",
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
            email="test2@test3.com",
            age=22,
            weight=61,
            height=172,
            gender=2,
            special_condition=1,
            body_activity=1,
            vegetables_in_one_day=1,
            fruits_in_one_day=1,
            fried_food_in_one_day=1,
            sweet_snacks_in_one_day=1,
            sweet_drinks_in_one_day=1,
            packaged_food_in_one_day=1,
            large_meal_in_one_day=1,
            snacks_in_one_day=1,
            breakfast_type=1,
            current_condition=1,
            problem_to_solve=1,
            health_problem=[2, 3])
        
        cls.diet_profile_3 = DietProfile.objects.create(
            name="test22",
            email="test22@test3.com",
            age=22,
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
            weight=61,
            height=172,
            gender=2,
            special_condition=1,
            body_activity=1,
            vegetables_in_one_day=1,
            fruits_in_one_day=1,
            fried_food_in_one_day=1,
            sweet_snacks_in_one_day=1,
            sweet_drinks_in_one_day=1,
            packaged_food_in_one_day=1,
            large_meal_in_one_day=1,
            snacks_in_one_day=1,
            breakfast_type=1,
            current_condition=1,
            problem_to_solve=1,
            health_problem=[2, 3])

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        cls.nutritionist = Nutritionist.objects.create(
            id=1,
            full_name_and_degree="Test, S.Gz",
            registration_certificate_no="1234567890",
            university="Universitas Indonesia",
            mastered_nutritional_problems="Manajemen berat badan, hipertensi",
            handled_age_group="12-17 tahun (Remaja)",
            another_practice_place="RSCM",
            languages="Bahasa Indonesia, Bahasa Inggris",
        )

        cls.custom_user_1 = CustomUser.objects.create_user(
            name='tes', 
            email='test@test.com', 
            password='abc',
103
104
105
            diet_profile=cls.diet_profile_1,
            nutritionist=cls.nutritionist
        )
106

107
108
109
110
111
112
113
        cls.custom_user_2 = CustomUser.objects.create_user(
            name='tes',
            email='email2@gmail.com',
            password='abc',
            diet_profile=cls.diet_profile_2,
            nutritionist=cls.nutritionist
        )
114
115
116
117
118
119

        cls.custom_user_3 = CustomUser.objects.create_user(
            name='tesb', 
            email='test2@2test.com', 
            password='abc',
            nutritionist=cls.nutritionist)
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

        cls.diet_questionnaire_1 = DietQuestionnaire.objects.create(
            user=cls.custom_user_1,
            agree_to_all_statements_consent=1,
            personal_data_consent=1
        )

        cls.diet_recommendation_1 = DietRecommendation.objects.create(
            client=cls.custom_user_1,
            nutritionist=cls.custom_user_1.nutritionist
        )

        cls.diet_questionnaire_2 = DietQuestionnaire.objects.create(
            user=cls.custom_user_2,
            agree_to_all_statements_consent=1,
            personal_data_consent=1
        )

        cls.diet_recommendation_2 = DietRecommendation.objects.create(
            client=cls.custom_user_2,
            nutritionist=cls.custom_user_2.nutritionist
        )
142
143
144
145
146
147
148
        
        cls.g0 = Group.objects.get(name='client')
        cls.g0.user_set.remove(cls.custom_user_3)

        cls.g1 = Group.objects.create(name='nutritionist')
        cls.g1.user_set.add(cls.custom_user_3)

149
150
151
152
153
154
155
        cls.custom_user_4 = CustomUser.objects.create_user(
            name='tes', 
            email='tesst@test.com', 
            password='abc',
            diet_profile=cls.diet_profile_3,
            nutritionist=cls.nutritionist)

156
157
158
    def test_get_all_users(self):
        response = self.client.get(self.BASE_URL)

159
        expected_response = []
160
        users = CustomUser.objects.all()
161
162
163
164
165
166
167
168
169
170
171
        for user in users:
            expected_response.append({
                'user': CustomUserDetailsSerializer(user).data,
                'diet_profile_id': user.diet_profile.id \
                    if user.diet_profile is not None else None,
                'diet_questionnaire_id': user.diet_questionnaire.id \
                    if hasattr(user, 'diet_questionnaire') else None,
                'diet_recommendation_id': user.diet_recommendation.id \
                    if hasattr(user, 'diet_recommendation') else None
            })
        self.assertEqual(response.data, expected_response)
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_user_belonging_to_a_nutritionist(self):
        response = self.client.get(self.BASE_URL,secure=True)

        data = {
            'email': 'test2@2test.com',
            'password': 'abc',
            'role': 'nutritionist',
        }

        response = self.client.post('/auth/user-login/', data, format='json')
        json_response = json.loads(response.content)

        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + json_response['access_token'])
        response = self.client.get(self.BASE_URL,secure=True)
        users = CustomUser.objects.filter(Q(nutritionist=1) & ~Q(email='test2@2test.com'))
189
190
191
192
193
194
195
196
197
198
199
200
        expected_response = []
        for user in users:
            expected_response.append({
                'user': CustomUserDetailsSerializer(user).data,
                'diet_profile_id': user.diet_profile.id \
                    if user.diet_profile is not None else None,
                'diet_questionnaire_id': user.diet_questionnaire.id \
                    if hasattr(user, 'diet_questionnaire') else None,
                'diet_recommendation_id': user.diet_recommendation.id \
                    if hasattr(user, 'diet_recommendation') else None
            })
        self.assertEqual(response.data, expected_response)
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
        self.assertEqual(response.status_code, status.HTTP_200_OK)
    
    def test_get_user_by_non_nutritionist(self):
        response = self.client.get(self.BASE_URL,secure=True)

        data = {
            'email': 'email2@gmail.com',
            'password': 'abc',
            'role' : 'client',
        }

        response = self.client.post('/auth/user-login/', data, format='json')
        json_response = json.loads(response.content)

        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + json_response['access_token'])
        response = self.client.get(self.BASE_URL,secure=True)
        users = CustomUser.objects.all()
218
219
220
221
222
223
224
225
226
227
228
229
        expected_response = []
        for user in users:
            expected_response.append({
                'user': CustomUserDetailsSerializer(user).data,
                'diet_profile_id': user.diet_profile.id \
                    if user.diet_profile is not None else None,
                'diet_questionnaire_id': user.diet_questionnaire.id \
                    if hasattr(user, 'diet_questionnaire') else None,
                'diet_recommendation_id': user.diet_recommendation.id \
                    if hasattr(user, 'diet_recommendation') else None
            })
        self.assertEqual(response.data, expected_response)
230
        self.assertEqual(response.status_code, status.HTTP_200_OK)
231
232
233
234
    
    def test_get_csv(self):
        response = self.client.get('/exportcsv/')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
235
236


237
238
class DietRecommendationTests(APITestCase):

239
240
    client = APIClient()

241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    @classmethod
    def setUpTestData(cls):
        cls.BASE_URL = "/diet-recommendation/"

        cls.nutritionist = Nutritionist.objects.create(
            id=1,
            full_name_and_degree="Test, S.Gz",
            registration_certificate_no="1234567890",
            university="Universitas Indonesia",
            mastered_nutritional_problems="Manajemen berat badan, hipertensi",
            handled_age_group="12-17 tahun (Remaja)",
            another_practice_place="RSCM",
            languages="Bahasa Indonesia, Bahasa Inggris",
        )

        cls.custom_user_1 = CustomUser.objects.create_user(
            name='tes',
            email='email@email.com',
            password='abc',
            nutritionist=cls.nutritionist
        )

        cls.custom_user_2 = CustomUser.objects.create_user(
            name='tes2',
            email='email2@email.com',
            password='abc',
            nutritionist=cls.nutritionist
        )

        cls.diet_recommendation = DietRecommendation.objects.create(
            client=cls.custom_user_2,
            nutritionist=cls.custom_user_2.nutritionist
        )

        cls.SPECIFIC_URL = f"{cls.BASE_URL}{cls.diet_recommendation.id}/"

277
278
279
280
281
282
283
284
285
286
        cls.login_data = {
            'email': 'email2@email.com',
            'password': 'abc',
            'role': 'client',
        }

        cls.login_response = cls.client.post('/auth/user-login/', cls.login_data, format='json')
        cls.json_login_response = json.loads(cls.login_response.content)
        cls.login_credentials = "Bearer " + cls.json_login_response['access_token']

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    def test_string_representation(self):
        self.assertEqual(str(self.diet_recommendation), 'email2@email.com - Test, S.Gz')

    def test_create_diet_recommendation_succeed(self):
        tmp_file = SimpleUploadedFile("testfile.pdf", bytes("abc", 'utf-8'), content_type="application/pdf")
        data = {
            'client': self.custom_user_1.id,
            'nutritionist': self.custom_user_1.nutritionist.id,
            'client_plan_meal': tmp_file,
            'nutritional_advice': 'baik baik ya',
            'lifestyle_advice': 'baik baik ya',
        }

        response = self.client.post(self.BASE_URL, data, format='multipart')
        json_response = json.loads(response.content)
        self.assertIn('.pdf', json_response.get('client_plan_meal'))
        self.assertEqual(json_response.get('client'), self.custom_user_1.id)
        self.assertEqual(json_response.get('nutritionist'), self.custom_user_1.nutritionist.id)
        self.assertEqual(json_response.get('nutritional_advice'), 'baik baik ya')
        self.assertEqual(json_response.get('lifestyle_advice'), 'baik baik ya')
        self.assertEqual(DietRecommendation.objects.count(), 2)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_diet_recommendation_failed(self):
        data = {
            'client': self.custom_user_1.id,
            'nutritionist': self.custom_user_1.nutritionist.id,
            'client_plan_meal': 'tesfile.pdf',
            'nutritional_advice': 'baik baik ya',
            'lifestyle_advice': 'baik baik ya',
        }

        response = self.client.post(self.BASE_URL, data, format='multipart')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_get_all_diet_recommendation(self):
323
        self.client.credentials(HTTP_AUTHORIZATION=self.login_credentials)
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        response = self.client.get(self.BASE_URL)
        json_response = json.loads(response.content)
        self.assertEqual(len(json_response), 1)
        self.assertEqual(json_response[0].get('client'), self.custom_user_2.id)
        self.assertEqual(json_response[0].get('nutritionist'), self.custom_user_2.nutritionist.id)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_single_diet_recommendation_succeed(self):
        response = self.client.get(self.SPECIFIC_URL)
        json_response = json.loads(response.content)
        self.assertEqual(json_response.get('client'), self.custom_user_2.id)
        self.assertEqual(json_response.get('nutritionist'), self.custom_user_2.nutritionist.id)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_single_diet_recommendation_failed(self):
        response = self.client.get(f"{self.BASE_URL}-1/")
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_update_diet_recommendation_succeed(self):
        tmp_file = SimpleUploadedFile("testfile2.pdf", bytes("abc", 'utf-8'), content_type="application/pdf")
        data = {
            'client_plan_meal': tmp_file,
            'nutritional_advice': 'makan yang banyak ya',
            'lifestyle_advice': 'yuk hidup sehat'
        }

        response = self.client.patch(self.SPECIFIC_URL, data, format='multipart')
        json_response = json.loads(response.content)
        self.assertEqual(json_response.get('client'), self.custom_user_2.id)
        self.assertEqual(json_response.get('nutritionist'), self.custom_user_2.nutritionist.id)
        self.assertIn('.pdf', json_response.get('client_plan_meal'))
        self.assertEqual(json_response.get('nutritional_advice'), 'makan yang banyak ya')
        self.assertEqual(json_response.get('lifestyle_advice'), 'yuk hidup sehat')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_update_diet_recommendation_failed(self):
        data = {
            'client_plan_meal': 'testfile2.pdf',
            'nutritional_advice': 'makan yang banyak ya',
            'lifestyle_advice': 'yuk hidup sehat'
        }

        response = self.client.post(self.BASE_URL, data, format='multipart')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)