test_collate.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from django.db import connection
  2. from django.db.models import F, Value
  3. from django.db.models.functions import Collate
  4. from django.test import TestCase
  5. from ..models import Author
  6. class CollateTests(TestCase):
  7. @classmethod
  8. def setUpTestData(cls):
  9. cls.author1 = Author.objects.create(alias='a', name='Jones 1')
  10. cls.author2 = Author.objects.create(alias='A', name='Jones 2')
  11. def test_collate_filter_ci(self):
  12. collation = connection.features.test_collations.get('ci')
  13. if not collation:
  14. self.skipTest(
  15. 'This backend does not support case-insensitive collations.'
  16. )
  17. qs = Author.objects.filter(alias=Collate(Value('a'), collation))
  18. self.assertEqual(qs.count(), 2)
  19. def test_collate_order_by_cs(self):
  20. collation = connection.features.test_collations.get('cs')
  21. if not collation:
  22. self.skipTest(
  23. 'This backend does not support case-sensitive collations.'
  24. )
  25. qs = Author.objects.order_by(Collate('alias', collation))
  26. self.assertSequenceEqual(qs, [self.author2, self.author1])
  27. def test_language_collation_order_by(self):
  28. collation = connection.features.test_collations.get('swedish-ci')
  29. if not collation:
  30. self.skipTest('This backend does not support language collations.')
  31. author3 = Author.objects.create(alias='O', name='Jones')
  32. author4 = Author.objects.create(alias='Ö', name='Jones')
  33. author5 = Author.objects.create(alias='P', name='Jones')
  34. qs = Author.objects.order_by(Collate(F('alias'), collation), 'name')
  35. self.assertSequenceEqual(
  36. qs,
  37. [self.author1, self.author2, author3, author5, author4],
  38. )
  39. def test_invalid_collation(self):
  40. tests = [
  41. None,
  42. '',
  43. 'et-x-icu" OR ',
  44. '"schema"."collation"',
  45. ]
  46. msg = "Invalid collation name: %r."
  47. for value in tests:
  48. with self.subTest(value), self.assertRaisesMessage(ValueError, msg % value):
  49. Collate(F('alias'), value)