testing.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from django.contrib.auth.models import Permission, User
  2. from rest_framework.test import APITestCase as _APITestCase
  3. from users.models import Token
  4. class APITestCase(_APITestCase):
  5. def setUp(self):
  6. """
  7. Create a superuser and token for API calls.
  8. """
  9. self.user = User.objects.create(username='testuser', is_superuser=True)
  10. self.token = Token.objects.create(user=self.user)
  11. self.header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token.key)}
  12. def assertHttpStatus(self, response, expected_status):
  13. """
  14. Provide more detail in the event of an unexpected HTTP response.
  15. """
  16. err_message = "Expected HTTP status {}; received {}: {}"
  17. self.assertEqual(response.status_code, expected_status, err_message.format(
  18. expected_status, response.status_code, getattr(response, 'data', 'No data')
  19. ))
  20. def create_test_user(username='testuser', permissions=list()):
  21. """
  22. Create a User with the given permissions.
  23. """
  24. user = User.objects.create_user(username=username)
  25. for perm_name in permissions:
  26. app, codename = perm_name.split('.')
  27. perm = Permission.objects.get(content_type__app_label=app, codename=codename)
  28. user.user_permissions.add(perm)
  29. return user
  30. def choices_to_dict(choices_list):
  31. """
  32. Convert a list of field choices to a dictionary suitable for direct comparison with a ChoiceSet. For example:
  33. [
  34. {
  35. "value": "choice-1",
  36. "label": "First Choice"
  37. },
  38. {
  39. "value": "choice-2",
  40. "label": "Second Choice"
  41. }
  42. ]
  43. Becomes:
  44. {
  45. "choice-1": "First Choice",
  46. "choice-2": "Second Choice
  47. }
  48. """
  49. return {
  50. choice['value']: choice['label'] for choice in choices_list
  51. }