test_repeat.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from django.db import connection
  2. from django.db.models import Value
  3. from django.db.models.functions import Length, Repeat
  4. from django.test import TestCase
  5. from ..models import Author
  6. class RepeatTests(TestCase):
  7. def test_basic(self):
  8. Author.objects.create(name="John", alias="xyz")
  9. none_value = (
  10. "" if connection.features.interprets_empty_strings_as_nulls else None
  11. )
  12. tests = (
  13. (Repeat("name", 0), ""),
  14. (Repeat("name", 2), "JohnJohn"),
  15. (Repeat("name", Length("alias")), "JohnJohnJohn"),
  16. (Repeat(Value("x"), 3), "xxx"),
  17. (Repeat("name", None), none_value),
  18. (Repeat(Value(None), 4), none_value),
  19. (Repeat("goes_by", 1), none_value),
  20. )
  21. for function, repeated_text in tests:
  22. with self.subTest(function=function):
  23. authors = Author.objects.annotate(repeated_text=function)
  24. self.assertQuerySetEqual(
  25. authors, [repeated_text], lambda a: a.repeated_text, ordered=False
  26. )
  27. def test_negative_number(self):
  28. with self.assertRaisesMessage(
  29. ValueError, "'number' must be greater or equal to 0."
  30. ):
  31. Repeat("name", -1)