Advertisement
Guest User

Untitled

a guest
Nov 20th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.15 KB | None | 0 0
  1. import ast
  2. from unittest import skipUnless
  3.  
  4. from django.core.urlresolvers import reverse
  5. from django.utils import timezone
  6. from django.conf import settings
  7.  
  8. from rest_framework import status
  9. from rest_framework.test import APITestCase, APIClient
  10. from oauth2_provider.models import Application
  11.  
  12. from sibylsurveys.modules.surveys.factories import SurveyFactory
  13. from sibylsurveys.modules.devices.models import GCMDevice
  14. from sibylsurveys.modules.devices.factories import GCMDeviceFactory
  15. from sibylsurveys.modules.engagements.factories import EngagementFactory
  16. from sibylsurveys.common.utils.constants import responsibyl_identifier_header
  17. from sibylsurveys.common.serializers import TimestampField
  18. from sibylsurveys.modules.profiles.factories import UserProfileFactory
  19.  
  20.  
  21. class UpdateProfileTestCase(APITestCase):
  22. def setUp(self):
  23. self.test_profile1 = UserProfileFactory(username='user1', email='fake1@gmail.com')
  24. self.test_company = self.test_profile1.company
  25.  
  26. self.app = Application.objects.create(
  27. user=self.test_profile1.user,
  28. client_type=Application.CLIENT_PUBLIC,
  29. authorization_grant_type=Application.GRANT_PASSWORD,
  30. name='test app',
  31. client_id='VwYwTabLDcPXrTGlvz8hycTX8Q0nYndkeVJDj91C',
  32. client_secret='XmAbDtQRQKAKp70LVDyACdGoixN1F3FjnU8woTTyGSTHLhzkIfAYjctegDXKxxjuqkl7IgfmpMVKpHv8MuKUhmXx5zQNTK97p7AqQf09dj8P5DzAZCEkRcKkWufDhDOt'
  33. )
  34.  
  35. self.test_profile2 = UserProfileFactory(username='user2', email='fake2@gmail.com')
  36.  
  37. self.client = APIClient()
  38. self.client.login(username='user1', password='pass')
  39.  
  40. self.test_engagement = EngagementFactory(owner=self.test_profile1)
  41. self.test_device1 = GCMDeviceFactory(last_user_logged=self.test_profile1, current_user=None)
  42. self.test_device2 = GCMDeviceFactory(last_user_logged=self.test_profile1, current_user=None)
  43. self.test_survey = SurveyFactory(responses_goal=100, engagement=self.test_engagement)
  44.  
  45. self.test_datetime_to_timestamp = TimestampField(field_type='datetime').to_representation(
  46. timezone.datetime(year=1973, month=11, day=11, hour=21, minute=33, second=9))
  47.  
  48. @skipUnless(settings.API in ['BO', 'APP'], 'API is either "APP" or "BO".')
  49. def test_last_online(self):
  50. """
  51. First, both last online and last sync time are null.
  52. First request, throws exception, but sets last online. Sync still null.
  53. Second request, success, updates last online to a greater time. Sync still null.
  54. :return:
  55. """
  56. self.assertIsNone(self.test_profile1.last_online)
  57. self.assertIsNone(self.test_profile1.last_sync)
  58.  
  59. self.client.get('/api/v1/something/')
  60. self.test_profile1.refresh_from_db()
  61. self.assertIsNotNone(self.test_profile1.last_online)
  62.  
  63. last_online = self.test_profile1.last_online
  64. self.client.get('/api/v1/user/')
  65. self.test_profile1.refresh_from_db()
  66.  
  67. self.assertGreater(self.test_profile1.last_online, last_online)
  68. self.assertIsNone(self.test_profile1.last_sync)
  69.  
  70. print('test_last_online PASSED')
  71.  
  72. @skipUnless(settings.API == 'APP', 'API must be "APP".')
  73. def test_last_sync(self):
  74. """
  75. Last sync is null, after the request it should be almost equal to the post time.
  76. :return:
  77. """
  78. self.assertIsNone(self.test_profile1.last_sync)
  79.  
  80. url = reverse('responses:survey-response-list', kwargs={'survey_id': self.test_survey.id})
  81. data_to_send = {
  82. 'question_screen_responses': [],
  83. 'taken': self.test_datetime_to_timestamp,
  84. 'duration': '00:10:00',
  85. 'latitude': 5,
  86. 'longitude': 15,
  87. 'device': self.test_device1.id,
  88. 'respondent': {
  89. 'gender': 1,
  90. 'age': 18
  91. }
  92. }
  93. self.client.credentials(**{
  94. responsibyl_identifier_header: self.test_device1.id
  95. })
  96. post_time = (timezone.datetime.now(timezone.get_current_timezone()) - timezone.datetime(1970, 1, 1, 0, 0, 0, 0, timezone.get_current_timezone())).total_seconds()
  97. self.client.post(url, data_to_send, format='json')
  98.  
  99. self.test_profile1.refresh_from_db()
  100. self.assertIsNotNone(self.test_profile1.last_sync)
  101. last_sync = (timezone.make_aware(self.test_profile1.last_sync,
  102. timezone.get_current_timezone()) - timezone.datetime(1970, 1, 1, 0, 0, 0, 0, timezone.get_current_timezone())).total_seconds()
  103. self.assertAlmostEqual(int(post_time), int(last_sync))
  104.  
  105. print('test_last_sync PASSED')
  106.  
  107. @skipUnless(settings.API == 'APP', 'API must be "APP".')
  108. def test_current_device(self):
  109. """
  110. Initial device is null.
  111. First request - user logs in, so it becomes current user on the device.
  112. Second request - user logs out, so current user becomes null.
  113. :return:
  114. """
  115.  
  116. self.assertIsNone(self.test_device1.current_user)
  117. self.client.credentials(**{
  118. responsibyl_identifier_header: self.test_device2.id
  119. })
  120. url = '/oauth2/token/'
  121. url_params = {
  122. 'grant_type': 'password',
  123. 'client_id': self.app.client_id,
  124. 'client_secret': self.app.client_secret,
  125. 'username': self.test_profile1.username,
  126. 'password': 'pass',
  127. }
  128.  
  129. post_url = url + '?'
  130. for parameter, value in url_params.iteritems():
  131. post_url += parameter + '=' + value + '&'
  132. post_url = post_url[:-1]
  133. response = self.client.post(post_url)
  134.  
  135. self.client.post(post_url, format='json')
  136.  
  137. self.assertEqual(response.status_code, status.HTTP_200_OK)
  138. self.test_device2 = GCMDevice.objects.get(pk=self.test_device2.id)
  139. self.assertEqual(self.test_device2.current_user, self.test_profile1)
  140.  
  141. url = '/oauth2/revoke_token/'
  142. token = ast.literal_eval(response.content)['access_token']
  143. post_url = url + '?token={}&client_id={}'.format(token, self.app.client_id)
  144. response = self.client.post(post_url)
  145.  
  146. self.assertEqual(response.status_code, status.HTTP_200_OK)
  147. self.test_device2 = GCMDevice.objects.get(pk=self.test_device2.id)
  148. self.assertEqual(self.test_device2.current_user, None)
  149.  
  150. print('test_current_device PASSED')
  151.  
  152. @skipUnless(settings.API in ['BO', 'APP'], 'API is either "APP" or "BO".')
  153. def test_change_user_password(self):
  154. # Anon client, should not work.
  155. url = reverse('profiles:user-change-password')
  156. data_to_send = {
  157. 'old_password': 'pass',
  158. 'new_password': 'pass',
  159. 'confirm_password': 'pass'
  160. }
  161.  
  162. client = APIClient()
  163. response = client.post(url, data_to_send, format='json')
  164. self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
  165.  
  166. # Incorrect password
  167. data_to_send = {
  168. 'old_password': 'pass2',
  169. 'new_password': 'pas',
  170. 'confirm_password': 'pas'
  171. }
  172. response = self.client.post(url, data_to_send, format='json')
  173. self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
  174. self.assertEqual(response.data, {'old_password': ['Incorrect password.']})
  175.  
  176. # New password identical to old one
  177. data_to_send = {
  178. 'old_password': 'pass',
  179. 'new_password': 'pass',
  180. 'confirm_password': 'pass'
  181. }
  182. response = self.client.post(url, data_to_send, format='json')
  183. self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
  184. self.assertEqual(response.data, {'new_password': ["New password shouldn't match old password."]})
  185.  
  186. # Confirm password not matching
  187. data_to_send = {
  188. 'old_password': 'pass',
  189. 'new_password': 'pass2',
  190. 'confirm_password': 'pass1'
  191. }
  192. response = self.client.post(url, data_to_send, format='json')
  193. self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
  194. self.assertEqual(response.data, {'confirm_password': ["Passwords don't match."]})
  195.  
  196. # Password should contain at least 4 characters.
  197. data_to_send = {
  198. 'old_password': 'pass',
  199. 'new_password': 'pas',
  200. 'confirm_password': 'pas'
  201. }
  202. response = self.client.post(url, data_to_send, format='json')
  203. self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
  204.  
  205. # Current user
  206. data_to_send = {
  207. 'old_password': 'pass',
  208. 'new_password': 'newPass',
  209. 'confirm_password': 'newPass'
  210. }
  211. response = self.client.post(url, data_to_send, format='json')
  212.  
  213. # Check if password was changed.
  214. self.assertEqual(response.status_code, status.HTTP_200_OK)
  215.  
  216. self.client = APIClient()
  217. self.client.login(username='user1', password='pass')
  218.  
  219. print('test_change_user_password PASSED')
  220.  
  221. def tearDown(self):
  222. self.client.logout()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement