Debian Codegraph @

tests/db_functions/text/test_pad.py

raw
1 from django.db import connection
2 from django.db.models import Value
3 from django.db.models.functions import Length, LPad, RPad
4 from django.test import TestCase
5
6 from ..models import Author
7
8
9 class PadTests(TestCase):
10 def test_pad(self):
11 Author.objects.create(name="John", alias="j")
12 none_value = (
13 "" if connection.features.interprets_empty_strings_as_nulls else None
14 )
15 tests = (
16 (LPad("name", 7, Value("xy")), "xyxJohn"),
17 (RPad("name", 7, Value("xy")), "Johnxyx"),
18 (LPad("name", 6, Value("x")), "xxJohn"),
19 (RPad("name", 6, Value("x")), "Johnxx"),
20 # The default pad string is a space.
21 (LPad("name", 6), " John"),
22 (RPad("name", 6), "John "),
23 # If string is longer than length it is truncated.
24 (LPad("name", 2), "Jo"),
25 (RPad("name", 2), "Jo"),
26 (LPad("name", 0), ""),
27 (RPad("name", 0), ""),
28 (LPad("name", None), none_value),
29 (RPad("name", None), none_value),
30 (LPad(Value(None), 1), none_value),
31 (RPad(Value(None), 1), none_value),
32 (LPad("goes_by", 1), none_value),
33 (RPad("goes_by", 1), none_value),
34 )
35 for function, padded_name in tests:
36 with self.subTest(function=function):
37 authors = Author.objects.annotate(padded_name=function)
38 self.assertQuerySetEqual(
39 authors, [padded_name], lambda a: a.padded_name, ordered=False
40 )
41
42 def test_pad_negative_length(self):
43 for function in (LPad, RPad):
44 with self.subTest(function=function):
45 with self.assertRaisesMessage(
46 ValueError, "'length' must be greater or equal to 0."
47 ):
48 function("name", -1)
49
50 def test_combined_with_length(self):
51 Author.objects.create(name="Rhonda", alias="john_smith")
52 Author.objects.create(name="♥♣♠", alias="bytes")
53 authors = Author.objects.annotate(filled=LPad("name", Length("alias")))
54 self.assertQuerySetEqual(
55 authors.order_by("alias"),
56 [" ♥♣♠", " Rhonda"],
57 lambda a: a.filled,
58 )