Guest User

Untitled

a guest
Sep 11th, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. from django.test import TestCase
  2. from rest_framework.test import APIClient, APIRequestFactory
  3.  
  4. from users.factories import UserFactory
  5.  
  6.  
  7. API_BASE_URL = 'api'
  8.  
  9.  
  10. REQUEST_FACTORY = APIRequestFactory()
  11.  
  12.  
  13. class BaseAPIClient(APIClient):
  14.  
  15. def request(self, **kwargs):
  16. if 'PATH_INFO' in kwargs and not kwargs['PATH_INFO'].startswith('/{}/'.format(API_BASE_URL)):
  17. kwargs['PATH_INFO'] = '/{}/{}'.format(API_BASE_URL, kwargs['PATH_INFO'])
  18. return super().request(**kwargs)
  19.  
  20.  
  21. class BaseAPITest(TestCase):
  22. client_class = BaseAPIClient
  23.  
  24. DO_SETUP = True
  25.  
  26. def setUp(self):
  27. if self.DO_SETUP:
  28. self.longMessage = True
  29. self.password = 'password'
  30. self.user = UserFactory.create(
  31. email='tester@example.com', username='tester@example.com', password=self.password)
  32. self.user2 = UserFactory.create(
  33. email='tester2@example.com', username='tester2@example.com', password=self.password)
  34. self.login_user(self.user)
  35.  
  36. def login_user(self, user):
  37. self.client.login(username=user.email, password='password')
  38.  
  39. def get_request_context(self):
  40. request = REQUEST_FACTORY.request()
  41. request.user = self.user
  42. return {
  43. 'request': request
  44. }
  45.  
  46. def _request_and_check_status(self, method_name, url, expected_status, data=None, full_response=False):
  47. method = getattr(self.client, method_name)
  48. response = method(url, data, format='json')
  49. self.assertEqual(expected_status, response.status_code, getattr(response, 'data', None))
  50. if full_response:
  51. return response
  52. return getattr(response, 'data', None)
  53.  
  54. def get_and_check_status(self, url, expected_status, data=None, full_response=False):
  55. return self._request_and_check_status('get', url, expected_status, data, full_response=full_response)
  56.  
  57. def post_and_check_status(self, url, data, expected_status, full_response=False):
  58. return self._request_and_check_status('post', url, expected_status, data, full_response=full_response)
  59.  
  60. def delete_and_check_status(self, url, expected_status, full_response=False):
  61. return self._request_and_check_status('delete', url, expected_status, full_response=full_response)
  62.  
  63. def patch_and_check_status(self, url, data, expected_status, full_response=False):
  64. return self._request_and_check_status('patch', url, expected_status, data, full_response=full_response)
  65.  
  66. def serializer_fields_check(self, serializer):
  67. self.assertEqual(self.expected_fields, set(serializer.data.keys()), 'Serializer keys differ from the expected')
Add Comment
Please, Sign In to add comment