test_right.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from django.db.models import IntegerField, 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(
  13. authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part
  14. )
  15. # If alias is null, set it to the first 2 lower characters of the name.
  16. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2)))
  17. self.assertQuerySetEqual(
  18. authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
  19. )
  20. def test_invalid_length(self):
  21. with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
  22. Author.objects.annotate(raises=Right("name", 0))
  23. def test_expressions(self):
  24. authors = Author.objects.annotate(
  25. name_part=Right("name", Value(3, output_field=IntegerField()))
  26. )
  27. self.assertQuerySetEqual(
  28. authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part
  29. )