Debian Codegraph @

tests/db_functions/text/test_right.py

raw
1 from django.db import connection
2 from django.db.models import IntegerField, Value
3 from django.db.models.functions import Length, Lower, Right
4 from django.test import TestCase
5
6 from ..models import Author
7
8
9 class RightTests(TestCase):
10 @classmethod
11 def setUpTestData(cls):
12 Author.objects.create(name="John Smith", alias="smithj")
13 Author.objects.create(name="Rhonda")
14
15 def test_basic(self):
16 authors = Author.objects.annotate(name_part=Right("name", 5))
17 self.assertQuerySetEqual(
18 authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part
19 )
20 # If alias is null, set it to the first 2 lower characters of the name.
21 Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2)))
22 self.assertQuerySetEqual(
23 authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
24 )
25
26 def test_invalid_length(self):
27 with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
28 Author.objects.annotate(raises=Right("name", 0))
29
30 def test_zero_length(self):
31 Author.objects.create(name="Tom", alias="tom")
32 authors = Author.objects.annotate(
33 name_part=Right("name", Length("name") - Length("alias"))
34 )
35 self.assertQuerySetEqual(
36 authors.order_by("name"),
37 [
38 "mith",
39 "" if connection.features.interprets_empty_strings_as_nulls else None,
40 "",
41 ],
42 lambda a: a.name_part,
43 )
44
45 def test_expressions(self):
46 authors = Author.objects.annotate(
47 name_part=Right("name", Value(3, output_field=IntegerField()))
48 )
49 self.assertQuerySetEqual(
50 authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part
51 )