test_trim.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from django.db.models import CharField
  2. from django.db.models.functions import LTrim, RTrim, Trim
  3. from django.test import TestCase
  4. from django.test.utils import register_lookup
  5. from ..models import Author
  6. class TrimTests(TestCase):
  7. def test_trim(self):
  8. Author.objects.create(name=" John ", alias="j")
  9. Author.objects.create(name="Rhonda", alias="r")
  10. authors = Author.objects.annotate(
  11. ltrim=LTrim("name"),
  12. rtrim=RTrim("name"),
  13. trim=Trim("name"),
  14. )
  15. self.assertQuerySetEqual(
  16. authors.order_by("alias"),
  17. [
  18. ("John ", " John", "John"),
  19. ("Rhonda", "Rhonda", "Rhonda"),
  20. ],
  21. lambda a: (a.ltrim, a.rtrim, a.trim),
  22. )
  23. def test_trim_transform(self):
  24. Author.objects.create(name=" John ")
  25. Author.objects.create(name="Rhonda")
  26. tests = (
  27. (LTrim, "John "),
  28. (RTrim, " John"),
  29. (Trim, "John"),
  30. )
  31. for transform, trimmed_name in tests:
  32. with self.subTest(transform=transform):
  33. with register_lookup(CharField, transform):
  34. authors = Author.objects.filter(
  35. **{"name__%s" % transform.lookup_name: trimmed_name}
  36. )
  37. self.assertQuerySetEqual(authors, [" John "], lambda a: a.name)