| 1 |
from django.db import connection |
| 2 |
from django.db.models import CharField, Value |
| 3 |
from django.db.models.functions import Length, Reverse, Trim |
| 4 |
from django.test import TestCase |
| 5 |
from django.test.utils import register_lookup |
| 6 |
|
| 7 |
from ..models import Author |
| 8 |
|
| 9 |
|
| 10 |
class ReverseTests(TestCase): |
| 11 |
@classmethod |
| 12 |
def setUpTestData(cls): |
| 13 |
cls.john = Author.objects.create(name="John Smith", alias="smithj") |
| 14 |
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") |
| 15 |
cls.python = Author.objects.create(name="パイソン") |
| 16 |
|
| 17 |
def test_null(self): |
| 18 |
author = Author.objects.annotate(backward=Reverse("alias")).get( |
| 19 |
pk=self.python.pk |
| 20 |
) |
| 21 |
self.assertEqual( |
| 22 |
author.backward, |
| 23 |
"" if connection.features.interprets_empty_strings_as_nulls else None, |
| 24 |
) |
| 25 |
|
| 26 |
def test_basic(self): |
| 27 |
authors = Author.objects.annotate( |
| 28 |
backward=Reverse("name"), |
| 29 |
constant=Reverse(Value("static string")), |
| 30 |
) |
| 31 |
self.assertQuerySetEqual( |
| 32 |
authors, |
| 33 |
[ |
| 34 |
("John Smith", "htimS nhoJ", "gnirts citats"), |
| 35 |
("Élena Jordan", "nadroJ anelÉ", "gnirts citats"), |
| 36 |
("パイソン", "ンソイパ", "gnirts citats"), |
| 37 |
], |
| 38 |
lambda a: (a.name, a.backward, a.constant), |
| 39 |
ordered=False, |
| 40 |
) |
| 41 |
|
| 42 |
def test_transform(self): |
| 43 |
with register_lookup(CharField, Reverse): |
| 44 |
authors = Author.objects.all() |
| 45 |
self.assertCountEqual( |
| 46 |
authors.filter(name__reverse=self.john.name[::-1]), [self.john] |
| 47 |
) |
| 48 |
self.assertCountEqual( |
| 49 |
authors.exclude(name__reverse=self.john.name[::-1]), |
| 50 |
[self.elena, self.python], |
| 51 |
) |
| 52 |
|
| 53 |
def test_expressions(self): |
| 54 |
author = Author.objects.annotate(backward=Reverse(Trim("name"))).get( |
| 55 |
pk=self.john.pk |
| 56 |
) |
| 57 |
self.assertEqual(author.backward, self.john.name[::-1]) |
| 58 |
with register_lookup(CharField, Reverse), register_lookup(CharField, Length): |
| 59 |
authors = Author.objects.all() |
| 60 |
self.assertCountEqual( |
| 61 |
authors.filter(name__reverse__length__gt=7), [self.john, self.elena] |
| 62 |
) |
| 63 |
self.assertCountEqual( |
| 64 |
authors.exclude(name__reverse__length__gt=7), [self.python] |
| 65 |
) |