2
0

test_pad.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from django.db import connection
  2. from django.db.models import Value
  3. from django.db.models.functions import Length, LPad, RPad
  4. from django.test import TestCase
  5. from ..models import Author
  6. class PadTests(TestCase):
  7. def test_pad(self):
  8. Author.objects.create(name="John", alias="j")
  9. none_value = (
  10. "" if connection.features.interprets_empty_strings_as_nulls else None
  11. )
  12. tests = (
  13. (LPad("name", 7, Value("xy")), "xyxJohn"),
  14. (RPad("name", 7, Value("xy")), "Johnxyx"),
  15. (LPad("name", 6, Value("x")), "xxJohn"),
  16. (RPad("name", 6, Value("x")), "Johnxx"),
  17. # The default pad string is a space.
  18. (LPad("name", 6), " John"),
  19. (RPad("name", 6), "John "),
  20. # If string is longer than length it is truncated.
  21. (LPad("name", 2), "Jo"),
  22. (RPad("name", 2), "Jo"),
  23. (LPad("name", 0), ""),
  24. (RPad("name", 0), ""),
  25. (LPad("name", None), none_value),
  26. (RPad("name", None), none_value),
  27. (LPad(Value(None), 1), none_value),
  28. (RPad(Value(None), 1), none_value),
  29. (LPad("goes_by", 1), none_value),
  30. (RPad("goes_by", 1), none_value),
  31. )
  32. for function, padded_name in tests:
  33. with self.subTest(function=function):
  34. authors = Author.objects.annotate(padded_name=function)
  35. self.assertQuerySetEqual(
  36. authors, [padded_name], lambda a: a.padded_name, ordered=False
  37. )
  38. def test_pad_negative_length(self):
  39. for function in (LPad, RPad):
  40. with self.subTest(function=function):
  41. with self.assertRaisesMessage(
  42. ValueError, "'length' must be greater or equal to 0."
  43. ):
  44. function("name", -1)
  45. def test_combined_with_length(self):
  46. Author.objects.create(name="Rhonda", alias="john_smith")
  47. Author.objects.create(name="♥♣♠", alias="bytes")
  48. authors = Author.objects.annotate(filled=LPad("name", Length("alias")))
  49. self.assertQuerySetEqual(
  50. authors.order_by("alias"),
  51. [" ♥♣♠", " Rhonda"],
  52. lambda a: a.filled,
  53. )