test_filters.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. class ModelAdmin(admin.ModelAdmin):
  18. pass
  19. model = RelatedToTestModel
  20. field_path = 'field'
  21. field = get_fields_from_path(model, field_path)[-1]
  22. lookup_params = {}
  23. model_admin = ModelAdmin
  24. return field, lookup_params, model, model_admin, field_path
  25. def test_related_field_ajax_list_filter(self):
  26. request = self.factory.get('url')
  27. field, lookup_params, model, model_admin, field_path = self.get_related_field_ajax_list_filter_params()
  28. list_filter = RelatedFieldAjaxListFilter(field, request, lookup_params, model, model_admin, field_path)
  29. self.assertTrue(list_filter.has_output())
  30. choices = list_filter.field_choices(field, request, model_admin)
  31. self.assertIsInstance(choices, list)
  32. self.assertEqual(len(choices), 0)
  33. def test_related_field_ajax_list_filter_with_initial(self):
  34. initial = self.models[1]
  35. request = self.factory.get('url', {'field__id__exact': initial.pk})
  36. field, lookup_params, model, model_admin, field_path = self.get_related_field_ajax_list_filter_params()
  37. list_filter = RelatedFieldAjaxListFilter(field, request, lookup_params, model, model_admin, field_path)
  38. self.assertTrue(list_filter.has_output())
  39. choices = list_filter.field_choices(field, request, model_admin)
  40. self.assertIsInstance(choices, list)
  41. self.assertEqual(len(choices), 1)
  42. self.assertEqual(choices[0], (initial.pk, smart_text(initial)))