2019-01-09 01:12:10 +01:00
|
|
|
from django.db import connection
|
|
|
|
from django.db.models import CharField
|
|
|
|
from django.db.models.functions import Length, Reverse, Trim
|
|
|
|
from django.test import TestCase
|
|
|
|
from django.test.utils import register_lookup
|
|
|
|
|
|
|
|
from ..models import Author
|
|
|
|
|
|
|
|
|
|
|
|
class ReverseTests(TestCase):
|
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
2022-02-03 20:24:19 +01:00
|
|
|
cls.john = Author.objects.create(name="John Smith", alias="smithj")
|
|
|
|
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena")
|
|
|
|
cls.python = Author.objects.create(name="パイソン")
|
2019-01-09 01:12:10 +01:00
|
|
|
|
|
|
|
def test_null(self):
|
2022-02-03 20:24:19 +01:00
|
|
|
author = Author.objects.annotate(backward=Reverse("alias")).get(
|
|
|
|
pk=self.python.pk
|
|
|
|
)
|
|
|
|
self.assertEqual(
|
|
|
|
author.backward,
|
|
|
|
"" if connection.features.interprets_empty_strings_as_nulls else None,
|
|
|
|
)
|
2019-01-09 01:12:10 +01:00
|
|
|
|
|
|
|
def test_basic(self):
|
2022-02-03 20:24:19 +01:00
|
|
|
authors = Author.objects.annotate(backward=Reverse("name"))
|
2019-01-09 01:12:10 +01:00
|
|
|
self.assertQuerysetEqual(
|
|
|
|
authors,
|
|
|
|
[
|
2022-02-03 20:24:19 +01:00
|
|
|
("John Smith", "htimS nhoJ"),
|
|
|
|
("Élena Jordan", "nadroJ anelÉ"),
|
|
|
|
("パイソン", "ンソイパ"),
|
2019-01-09 01:12:10 +01:00
|
|
|
],
|
|
|
|
lambda a: (a.name, a.backward),
|
|
|
|
ordered=False,
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_transform(self):
|
|
|
|
with register_lookup(CharField, Reverse):
|
|
|
|
authors = Author.objects.all()
|
2022-02-03 20:24:19 +01:00
|
|
|
self.assertCountEqual(
|
|
|
|
authors.filter(name__reverse=self.john.name[::-1]), [self.john]
|
|
|
|
)
|
|
|
|
self.assertCountEqual(
|
|
|
|
authors.exclude(name__reverse=self.john.name[::-1]),
|
|
|
|
[self.elena, self.python],
|
|
|
|
)
|
2019-01-09 01:12:10 +01:00
|
|
|
|
|
|
|
def test_expressions(self):
|
2022-02-03 20:24:19 +01:00
|
|
|
author = Author.objects.annotate(backward=Reverse(Trim("name"))).get(
|
|
|
|
pk=self.john.pk
|
|
|
|
)
|
2019-01-09 01:12:10 +01:00
|
|
|
self.assertEqual(author.backward, self.john.name[::-1])
|
|
|
|
with register_lookup(CharField, Reverse), register_lookup(CharField, Length):
|
|
|
|
authors = Author.objects.all()
|
2022-02-03 20:24:19 +01:00
|
|
|
self.assertCountEqual(
|
|
|
|
authors.filter(name__reverse__length__gt=7), [self.john, self.elena]
|
|
|
|
)
|
|
|
|
self.assertCountEqual(
|
|
|
|
authors.exclude(name__reverse__length__gt=7), [self.python]
|
|
|
|
)
|