test_filters.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from django.contrib import admin
  2. from django.test import TestCase, RequestFactory
  3. from django.utils.encoding import smart_text
  4. from jet.filters import RelatedFieldAjaxListFilter
  5. from jet.tests.models import RelatedToTestModel, TestModel
  6. try:
  7. from django.contrib.admin.utils import get_fields_from_path
  8. except ImportError: # Django 1.6
  9. from django.contrib.admin.util import get_fields_from_path
  10. class FiltersTestCase(TestCase):
  11. def setUp(self):
  12. self.models = []
  13. self.factory = RequestFactory()
  14. self.models.append(TestModel.objects.create(field1='first', field2=1))
  15. self.models.append(TestModel.objects.create(field1='second', field2=2))
  16. def get_related_field_ajax_list_filter_params(self):
  17. model = RelatedToTestModel
  18. field_path = 'field'
  19. field = get_fields_from_path(model, field_path)[-1]
  20. lookup_params = {}
  21. model_admin = admin.site._registry.get(model)
  22. return field, lookup_params, model, model_admin, field_path
  23. def test_related_field_ajax_list_filter(self):
  24. request = self.factory.get('url')
  25. field, lookup_params, model, model_admin, field_path = self.get_related_field_ajax_list_filter_params()
  26. list_filter = RelatedFieldAjaxListFilter(field, request, lookup_params, model, model_admin, field_path)
  27. self.assertTrue(list_filter.has_output())
  28. choices = list_filter.field_choices(field, request, model_admin)
  29. self.assertIsInstance(choices, list)
  30. self.assertEqual(len(choices), 0)
  31. def test_related_field_ajax_list_filter_with_initial(self):
  32. initial = self.models[1]
  33. request = self.factory.get('url', {'field__id__exact': initial.pk})
  34. field, lookup_params, model, model_admin, field_path = self.get_related_field_ajax_list_filter_params()
  35. list_filter = RelatedFieldAjaxListFilter(field, request, lookup_params, model, model_admin, field_path)
  36. self.assertTrue(list_filter.has_output())
  37. choices = list_filter.field_choices(field, request, model_admin)
  38. self.assertIsInstance(choices, list)
  39. self.assertEqual(len(choices), 1)
  40. self.assertEqual(choices[0], (initial.pk, smart_text(initial)))