test_utils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from datetime import datetime, date
  2. import json
  3. from django.contrib.admin import AdminSite
  4. from django.test import TestCase
  5. from jet.tests.models import TestModel
  6. from jet.utils import JsonResponse, get_model_instance_label, get_app_list, get_admin_site, LazyDateTimeEncoder
  7. class UtilsTestCase(TestCase):
  8. def test_json_response(self):
  9. response = JsonResponse({'str': 'string', 'int': 1})
  10. response_dict = json.loads(response.content.decode())
  11. expected_dict = {"int": 1, "str": "string"}
  12. self.assertEqual(response_dict, expected_dict)
  13. self.assertEqual(response.get('Content-Type'), 'application/json')
  14. def test_get_model_instance_label(self):
  15. field1 = 'value'
  16. field2 = 2
  17. pinned_application = TestModel.objects.create(field1=field1, field2=field2)
  18. self.assertEqual(get_model_instance_label(pinned_application), '%s%d' % (field1, field2))
  19. def test_get_app_list(self):
  20. class User:
  21. is_active = True
  22. is_staff = True
  23. def has_module_perms(self, app):
  24. return True
  25. def has_perm(self, object):
  26. return True
  27. class Request:
  28. user = User()
  29. app_list = get_app_list({
  30. 'request': Request(),
  31. 'user': None
  32. })
  33. self.assertIsInstance(app_list, list)
  34. for app in app_list:
  35. self.assertIsInstance(app, dict)
  36. self.assertIsNotNone(app, app.get('models'))
  37. self.assertIsNotNone(app, app.get('app_url'))
  38. self.assertIsNotNone(app, app.get('app_label'))
  39. for model in app['models']:
  40. self.assertIsNotNone(app, model.get('object_name'))
  41. self.assertIsNotNone(app, model.get('name'))
  42. def test_get_admin_site(self):
  43. admin_site = get_admin_site({})
  44. self.assertIsInstance(admin_site, AdminSite)
  45. def test_lazy_date_time_encoder_dates(self):
  46. encoder = LazyDateTimeEncoder()
  47. ts = datetime.now()
  48. self.assertEqual(encoder.encode(ts), '"%s"' % ts.isoformat())
  49. ts = date(2015, 5, 3)
  50. self.assertEqual(encoder.encode(ts), '"%s"' % ts.isoformat())
  51. def test_lazy_date_time_encoder_dict(self):
  52. encoder = LazyDateTimeEncoder()
  53. self.assertEqual(encoder.encode({'key': 1}), '{"key": 1}')