2018-06-30 20:49:20 +00:00
|
|
|
from django.db import connection
|
2020-06-16 08:01:34 +00:00
|
|
|
from django.db.models import Value
|
2018-04-03 17:36:12 +00:00
|
|
|
from django.db.models.functions import Length, Repeat
|
|
|
|
from django.test import TestCase
|
|
|
|
|
2018-08-15 23:45:11 +00:00
|
|
|
from ..models import Author
|
2018-04-03 17:36:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class RepeatTests(TestCase):
|
|
|
|
def test_basic(self):
|
|
|
|
Author.objects.create(name="John", alias="xyz")
|
2018-06-30 20:49:20 +00:00
|
|
|
none_value = (
|
|
|
|
"" if connection.features.interprets_empty_strings_as_nulls else None
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2018-04-03 17:36:12 +00:00
|
|
|
tests = (
|
|
|
|
(Repeat("name", 0), ""),
|
|
|
|
(Repeat("name", 2), "JohnJohn"),
|
2020-06-16 08:01:34 +00:00
|
|
|
(Repeat("name", Length("alias")), "JohnJohnJohn"),
|
|
|
|
(Repeat(Value("x"), 3), "xxx"),
|
2018-06-30 20:49:20 +00:00
|
|
|
(Repeat("name", None), none_value),
|
2021-12-10 09:13:09 +00:00
|
|
|
(Repeat(Value(None), 4), none_value),
|
2018-06-30 20:49:20 +00:00
|
|
|
(Repeat("goes_by", 1), none_value),
|
2018-04-03 17:36:12 +00:00
|
|
|
)
|
|
|
|
for function, repeated_text in tests:
|
|
|
|
with self.subTest(function=function):
|
|
|
|
authors = Author.objects.annotate(repeated_text=function)
|
2022-09-24 10:29:58 +00:00
|
|
|
self.assertQuerySetEqual(
|
2018-04-03 17:36:12 +00:00
|
|
|
authors, [repeated_text], lambda a: a.repeated_text, ordered=False
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_negative_number(self):
|
|
|
|
with self.assertRaisesMessage(
|
|
|
|
ValueError, "'number' must be greater or equal to 0."
|
|
|
|
):
|
|
|
|
Repeat("name", -1)
|