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