test_right.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from django.db import connection
  2. from django.db.models import IntegerField, Value
  3. from django.db.models.functions import Length, Lower, Right
  4. from django.test import TestCase
  5. from ..models import Author
  6. class RightTests(TestCase):
  7. @classmethod
  8. def setUpTestData(cls):
  9. Author.objects.create(name="John Smith", alias="smithj")
  10. Author.objects.create(name="Rhonda")
  11. def test_basic(self):
  12. authors = Author.objects.annotate(name_part=Right("name", 5))
  13. self.assertQuerySetEqual(
  14. authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part
  15. )
  16. # If alias is null, set it to the first 2 lower characters of the name.
  17. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2)))
  18. self.assertQuerySetEqual(
  19. authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
  20. )
  21. def test_invalid_length(self):
  22. with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
  23. Author.objects.annotate(raises=Right("name", 0))
  24. def test_zero_length(self):
  25. Author.objects.create(name="Tom", alias="tom")
  26. authors = Author.objects.annotate(
  27. name_part=Right("name", Length("name") - Length("alias"))
  28. )
  29. self.assertQuerySetEqual(
  30. authors.order_by("name"),
  31. [
  32. "mith",
  33. "" if connection.features.interprets_empty_strings_as_nulls else None,
  34. "",
  35. ],
  36. lambda a: a.name_part,
  37. )
  38. def test_expressions(self):
  39. authors = Author.objects.annotate(
  40. name_part=Right("name", Value(3, output_field=IntegerField()))
  41. )
  42. self.assertQuerySetEqual(
  43. authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part
  44. )