test_right.py 1.2 KB

123456789101112131415161718192021222324252627
  1. from django.db.models import CharField, Value
  2. from django.db.models.functions import Lower, Right
  3. from django.test import TestCase
  4. from .models import Author
  5. class RightTests(TestCase):
  6. @classmethod
  7. def setUpTestData(cls):
  8. Author.objects.create(name='John Smith', alias='smithj')
  9. Author.objects.create(name='Rhonda')
  10. def test_basic(self):
  11. authors = Author.objects.annotate(name_part=Right('name', 5))
  12. self.assertQuerysetEqual(authors.order_by('name'), ['Smith', 'honda'], lambda a: a.name_part)
  13. # If alias is null, set it to the first 2 lower characters of the name.
  14. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right('name', 2)))
  15. self.assertQuerysetEqual(authors.order_by('name'), ['smithj', 'da'], lambda a: a.alias)
  16. def test_invalid_length(self):
  17. with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
  18. Author.objects.annotate(raises=Right('name', 0))
  19. def test_expressions(self):
  20. authors = Author.objects.annotate(name_part=Right('name', Value(3), output_field=CharField()))
  21. self.assertQuerysetEqual(authors.order_by('name'), ['ith', 'nda'], lambda a: a.name_part)