Fakultas Ilmu Komputer UI

tests.py 16 KB
Newer Older
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
1
import json
2
from unittest.mock import patch
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
3
from rest_framework import status
4
5
6
from rest_framework.test import APITestCase
from django.test import TestCase
from django.http import JsonResponse
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
7
from dietela_quiz.models import DietProfile
8
9
10
from payment.models import Cart
from dietela_program.models import DietelaProgram
from nutritionists.models import Nutritionist
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
11
from .models import CustomUser
12
13
14
from .serializers import (
    CustomLoginSerializer, CustomRegisterSerializer,CustomUserDetailsSerializer
)
15
from .google_utils import validate_google_token
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

class UserModelTests(APITestCase):

    @classmethod
    def setUpTestData(cls):
        cls.diet_profile_1 = DietProfile.objects.create(
            name="test",
            email="test@test.com",
            age=21,
            weight=70,
            height=173,
            gender=1,
            special_condition=2,
            body_activity=2,
            vegetables_in_one_day=2,
            fruits_in_one_day=2,
            fried_food_in_one_day=2,
            sweet_snacks_in_one_day=2,
            sweet_drinks_in_one_day=2,
            packaged_food_in_one_day=2,
            large_meal_in_one_day=2,
            snacks_in_one_day=2,
            breakfast_type=2,
            current_condition=2,
            problem_to_solve=2,
            health_problem=[1])

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        cls.diet_profile_2 = DietProfile.objects.create(
            name="test",
            email="email2@gmail.com",
            age=21,
            weight=70,
            height=173,
            gender=1,
            special_condition=2,
            body_activity=2,
            vegetables_in_one_day=2,
            fruits_in_one_day=2,
            fried_food_in_one_day=2,
            sweet_snacks_in_one_day=2,
            sweet_drinks_in_one_day=2,
            packaged_food_in_one_day=2,
            large_meal_in_one_day=2,
            snacks_in_one_day=2,
            breakfast_type=2,
            current_condition=2,
            problem_to_solve=2,
            health_problem=[1])

65
        cls.custom_user_1 = CustomUser.objects.create_user(name='tes', email='email@email.com', password='abc')
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
66

67
        cls.custom_user_2 = CustomUser.objects.create_user(name='tes', email='email2@gmail.com', password='abc')
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
68

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
69
70
71
72
        cls.inactive_user = CustomUser.objects.create_user(name='inactive', email='inactive@gmail.com', password='abc')
        cls.inactive_user.is_active = False
        cls.inactive_user.save()

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
73
74
75
        cls.num_of_diet_profile = DietProfile.objects.count()
        cls.num_of_custom_user = CustomUser.objects.count()

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        cls.dietela_program = DietelaProgram.objects.create(
            unique_code="PRG1",
            name="Program 1",
            price=350000.00,
        )

        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.cart = Cart.objects.create(program=cls.dietela_program, nutritionist=cls.nutritionist)

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
95
    def test_create_user(self):
96
97
        user = CustomUser.objects.create_user(name='tes', email='email2@email.com',
            password='tes', diet_profile=self.diet_profile_1,)
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
98
99
        self.assertEqual(str(user), 'email2@email.com')
        self.assertEqual(user.email, 'email2@email.com')
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
100
        self.assertTrue(user.groups.filter(name='client').exists())
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
        self.assertTrue(user.is_active)
        self.assertFalse(user.is_staff)
        self.assertFalse(user.is_superuser)
        try:
            # username is None for the AbstractUser option
            # username does not exist for the AbstractBaseUser option
            self.assertIsNone(user.username)
        except AttributeError:
            pass
        with self.assertRaises(TypeError):
            CustomUser.objects.create_user()
        with self.assertRaises(TypeError):
            CustomUser.objects.create_user(email='')
        with self.assertRaises(ValueError):
            CustomUser.objects.create_user(email='', password="tes")

    def test_create_superuser(self):
        admin_user = CustomUser.objects.create_superuser('super@user.com', 'foo')
        self.assertEqual(admin_user.email, 'super@user.com')
        self.assertTrue(admin_user.is_active)
        self.assertTrue(admin_user.is_staff)
        self.assertTrue(admin_user.is_superuser)
        try:
            # username is None for the AbstractUser option
            # username does not exist for the AbstractBaseUser option
            self.assertIsNone(admin_user.username)
        except AttributeError:
            pass
        with self.assertRaises(ValueError):
            CustomUser.objects.create_superuser(
                email='super@user.com', password='foo', is_superuser=False)
        with self.assertRaises(ValueError):
            CustomUser.objects.create_superuser(
                email='super@user.com', password='foo', is_staff=False)
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
135

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    def test_user_serializer(self):
        user_data = CustomUserDetailsSerializer(self.custom_user_1).data
        self.assertIn('email', user_data)
        self.assertIn('name', user_data)
        self.assertEqual('client', user_data.get('role'))
        self.assertIn('id', user_data)

        user_no_role = CustomUser()
        user_no_role.name = 'no role'
        user_no_role.email = 'norole@norole.com'
        user_no_role.password = 'norole2404'
        user_no_role.save()
        user_no_role_data = CustomUserDetailsSerializer(user_no_role).data
        self.assertTrue('role' not in user_no_role_data)

        admin_user = CustomUser.objects.create_superuser('super2@user.com', 'foo')
        admin_user_data = CustomUserDetailsSerializer(admin_user).data
        self.assertEqual('admin', admin_user_data.get('role'))

Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
155
156
    def test_post_registration_user_succeed(self):
        data = {
157
            'name': 'tes',
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
158
159
160
161
162
163
            'email': 'abc123@gmail.com',
            'password1': '2828abab',
            'password2': '2828abab',
        }

        response = self.client.post('/auth/registration/', data, format='json')
164
165
166
167
        json_response = json.loads(response.content)
        self.assertEqual(json_response.get('user').get('email'), 'abc123@gmail.com')
        self.assertEqual(json_response.get('user').get('role'), 'client')
        self.assertEqual(json_response.get('user').get('name'), 'tes')
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        self.assertEqual(CustomUser.objects.count(), self.num_of_custom_user + 1)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_post_registration_user_failed_because_invalid_email(self):
        data = {
            'email': 'abc123gmail.com',
            'password1': '2828abab',
            'password2': '2828abab',
        }

        response = self.client.post('/auth/registration/', data, format='json')
        self.assertEqual(CustomUser.objects.count(), self.num_of_custom_user)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_post_registration_user_failed_because_different_password(self):
        data = {
184
            'name': 'tes',
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
185
186
187
188
189
190
191
192
193
194
195
            'email': 'abc123@gmail.com',
            'password1': '2828abaab',
            'password2': '2828abab',
        }

        response = self.client.post('/auth/registration/', data, format='json')
        self.assertEqual(CustomUser.objects.count(), self.num_of_custom_user)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_post_registration_user_failed_because_email_already_registered(self):
        data = {
196
            'name': 'tes',
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
197
198
199
200
201
202
203
204
205
            'email': self.custom_user_1.email,
            'password1': '2828abaab',
            'password2': '2828abaab',
        }

        response = self.client.post('/auth/registration/', data, format='json')
        self.assertEqual(CustomUser.objects.count(), self.num_of_custom_user)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

206
207
208
209
210
211
212
213
    def test_create_registration_serializer_to_do_nothing(self):
        serializer = CustomRegisterSerializer()
        self.assertEqual(serializer.create({}), None)
    
    def test_update_registration_serializer_to_do_nothing(self):
        serializer = CustomRegisterSerializer()
        self.assertEqual(serializer.update(None, {}), None)

214
    def test_link_user_and_diet_profile_and_cart_succeed(self):
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
215
216
217
        data = {
            'email': self.custom_user_2.email,
            'diet_profile_id': self.diet_profile_2.id,
218
            'cart_id': self.cart.id,
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
219
220
        }

221
        response = self.client.post('/auth/link-data/', data, format='json')
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
222
223
224
225
        self.assertEqual(json.loads(response.content).get('user').get('email'), \
            self.custom_user_2.email)
        self.assertEqual(json.loads(response.content).get('diet_profile').get('id'), \
            self.diet_profile_2.id)
226
        self.assertEqual(json.loads(response.content).get('cart').get('id'), self.cart.id)
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
227
228
229
230
231
232
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_link_user_and_diet_profile_failed_because_email_doesnt_exist(self):
        data = {
            'email': 'emaill@gmail.com',
            'diet_profile_id': self.diet_profile_2.id,
233
            'cart_id': self.cart.id,
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
234
235
        }

236
        response = self.client.post('/auth/link-data/', data, format='json')
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
237
238
239
240
241
242
243
        self.assertEqual(json.loads(response.content).get('message'), 'User is not found.')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_link_user_and_diet_profile_failed_because_diet_profile_doesnt_exist(self):
        data = {
            'email': self.custom_user_2.email,
            'diet_profile_id': -1,
244
            'cart_id': self.cart.id,
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
245
246
        }

247
        response = self.client.post('/auth/link-data/', data, format='json')
Glenda Emanuella Sutanto's avatar
Glenda Emanuella Sutanto committed
248
249
        self.assertEqual(json.loads(response.content).get('message'), 'Diet profile is not found.')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
250

251
252
253
254
255
256
257
258
259
260
261
    def test_link_user_and_diet_profile_failed_because_cart_doesnt_exist(self):
        data = {
            'email': self.custom_user_2.email,
            'diet_profile_id': self.diet_profile_2.id,
            'cart_id': -1,
        }

        response = self.client.post('/auth/link-data/', data, format='json')
        self.assertEqual(json.loads(response.content).get('message'), 'Cart is not found.')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

262
263
264
265
    def test_post_login_user_succeed(self):
        data = {
            'email': 'email@email.com',
            'password': 'abc',
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
266
            'role': 'client',
267
268
        }

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
269
        response = self.client.post('/auth/user-login/', data, format='json')
270
271
272
273
        json_response = json.loads(response.content)
        self.assertIn('access_token', json_response)
        self.assertIn('refresh_token', json_response)
        self.assertIn('user', json_response)
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
274
275
        self.assertIn('id', json_response.get('user'))
        self.assertIn('role', json_response.get('user'))
276
        self.assertEquals(json_response.get('user').get('name'), 'tes')
277
278
279
280
281
282
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_post_login_user_failed_because_non_existing_email(self):
        data = {
            'email': 'email123123123@email.com',
            'password': 'abc',
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
283
            'role': 'client'
284
285
        }

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
286
287
288
289
290
291
292
293
294
295
296
        response = self.client.post('/auth/user-login/', data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    
    def test_post_login_user_failed_because_invalid_role(self):
        data = {
            'email': 'email@email.com',
            'password': 'abc',
            'role': 'artist'
        }

        response = self.client.post('/auth/user-login/', data, format='json')
297
298
299
300
301
302
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_post_login_user_failed_because_invalid_email_format(self):
        data = {
            'email': 'email123123123@email',
            'password': 'abc',
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
303
            'role': 'client'
304
305
        }

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
306
        response = self.client.post('/auth/user-login/', data, format='json')
307
308
309
310
311
312
313
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)


    def test_post_login_user_failed_because_invalid_password(self):
        data = {
            'email': 'email@email.com',
            'password': 'abc1234',
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
314
315
316
317
318
319
320
321
322
323
324
            'role': 'client'
        }

        response = self.client.post('/auth/user-login/', data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    
    def test_post_login_user_failed_because_inactive_account(self):
        data = {
            'email': 'inactive@gmail.com',
            'password': 'abc',
            'role': 'client'
325
        }
Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
326
327
        response = self.client.post('/auth/user-login/', data, format='json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
328

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
329
330
331
332
333
334
    def test_post_login_user_failed_because_no_role_in_payload(self):
        data = {
            'email': 'email@email.com',
            'password': 'abc',
        }
        response = self.client.post('/auth/user-login/', data, format='json')
335
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
336

Kefas Satrio Bangkit Solidedantyo's avatar
Kefas Satrio Bangkit Solidedantyo committed
337
338
339
340
341
342
343
344
    def test_create_login_serializer_to_do_nothing(self):
        serializer = CustomLoginSerializer()
        self.assertEqual(serializer.create({}), None)
    
    def test_update_login_serializer_to_do_nothing(self):
        serializer = CustomLoginSerializer()
        self.assertEqual(serializer.update(None, {}), None)

345
346
347
348
349
@patch('authentication.google_utils.requests.get')
@patch('authentication.google_utils.json.loads')
class TestValidateGoogleToken(TestCase):
    def test_validate_access_token_succeed(self, mock_json_loads, mock_get):
        mock_get.return_value.text = "ABCDEFGH"
350
        mock_json_loads.return_value = {"name": "mock", "email": 'mock_user@email.com'}
351
352
353
        success, google_data = validate_google_token("ABCDEFGH")

        self.assertTrue(success)
354
355
        self.assertEqual('mock_user@email.com', google_data.get('email'))
        self.assertEqual('mock', google_data.get('name'))
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

    def test_validate_access_token_failed(self, mock_json_loads, mock_get):
        mock_get.return_value.text = "123123123"
        mock_json_loads.return_value = {
            'error': 'invalid_token',
            'message': 'wrong google token / this google token is already expired.'
        }
        success, google_data = validate_google_token("123123123")

        self.assertFalse(success)
        self.assertEqual(google_data.status_code, status.HTTP_400_BAD_REQUEST)

@patch('authentication.views.validate_google_token')
class TestGoogleLogin(TestCase):
    def test_google_login_succeed(self, mock_validate_google_token):
371
        mock_validate_google_token.return_value = True, {"name": "tes", "email": 'email@email.com'}
372
373
374
375
376
377
378

        data = {'access_token': 'QWERTY'}
        response = self.client.post('/auth/google/', data, format='json')
        json_response = json.loads(response.content)
        self.assertIn('access_token', json_response)
        self.assertIn('refresh_token', json_response)
        self.assertIn('user', json_response)
379
380
381
        self.assertIn('role', json_response.get('user'))
        self.assertIn('name', json_response.get('user'))
        self.assertIn('email', json_response.get('user'))
382
383
384
385
386
387
388
389
390
391
392
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_google_login_failed(self, mock_validate_google_token):
        content = {'message': 'wrong google token / this google token is already expired.'}
        mock_validate_google_token.return_value = False, JsonResponse(content,
            status=status.HTTP_400_BAD_REQUEST)
        data = {'access_token': 'sdasdasdad'}
        response = self.client.post('/auth/google/', data, format='json')
        json_response = json.loads(response.content)
        self.assertIn('message', json_response)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)