test_left.py 1.2 KB

123456789101112131415161718192021222324252627
  1. from django.db.models import CharField, Value
  2. from django.db.models.functions import Left, Lower
  3. from django.test import TestCase
  4. from .models import Author
  5. class LeftTests(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=Left('name', 5))
  12. self.assertQuerysetEqual(authors.order_by('name'), ['John ', 'Rhond'], 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(Left('name', 2)))
  15. self.assertQuerysetEqual(authors.order_by('name'), ['smithj', 'rh'], 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=Left('name', 0))
  19. def test_expressions(self):
  20. authors = Author.objects.annotate(name_part=Left('name', Value(3), output_field=CharField()))
  21. self.assertQuerysetEqual(authors.order_by('name'), ['Joh', 'Rho'], lambda a: a.name_part)