test_chr.py 1.4 KB

1234567891011121314151617181920212223242526272829303132
  1. from django.db.models import IntegerField
  2. from django.db.models.functions import Chr, Left, Ord
  3. from django.test import TestCase
  4. from .models import Author
  5. class ChrTests(TestCase):
  6. @classmethod
  7. def setUpTestData(cls):
  8. cls.john = Author.objects.create(name='John Smith', alias='smithj')
  9. cls.elena = Author.objects.create(name='Élena Jordan', alias='elena')
  10. cls.rhonda = Author.objects.create(name='Rhonda')
  11. def test_basic(self):
  12. authors = Author.objects.annotate(first_initial=Left('name', 1))
  13. self.assertCountEqual(authors.filter(first_initial=Chr(ord('J'))), [self.john])
  14. self.assertCountEqual(authors.exclude(first_initial=Chr(ord('J'))), [self.elena, self.rhonda])
  15. def test_non_ascii(self):
  16. authors = Author.objects.annotate(first_initial=Left('name', 1))
  17. self.assertCountEqual(authors.filter(first_initial=Chr(ord('É'))), [self.elena])
  18. self.assertCountEqual(authors.exclude(first_initial=Chr(ord('É'))), [self.john, self.rhonda])
  19. def test_transform(self):
  20. try:
  21. IntegerField.register_lookup(Chr)
  22. authors = Author.objects.annotate(name_code_point=Ord('name'))
  23. self.assertCountEqual(authors.filter(name_code_point__chr=Chr(ord('J'))), [self.john])
  24. self.assertCountEqual(authors.exclude(name_code_point__chr=Chr(ord('J'))), [self.elena, self.rhonda])
  25. finally:
  26. IntegerField._unregister_lookup(Chr)