2018-07-01 04:49:20 +08:00
|
|
|
from django.db import connection
|
2020-06-16 16:01:34 +08:00
|
|
|
from django.db.models import Value
|
2018-04-04 00:24:04 +08:00
|
|
|
from django.db.models.functions import Length, LPad, RPad
|
2018-03-20 00:35:16 +08:00
|
|
|
from django.test import TestCase
|
|
|
|
|
2018-08-16 07:45:11 +08:00
|
|
|
from ..models import Author
|
2018-03-20 00:35:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
class PadTests(TestCase):
|
|
|
|
def test_pad(self):
|
|
|
|
Author.objects.create(name='John', alias='j')
|
2018-07-01 04:49:20 +08:00
|
|
|
none_value = '' if connection.features.interprets_empty_strings_as_nulls else None
|
2018-03-20 00:35:16 +08:00
|
|
|
tests = (
|
|
|
|
(LPad('name', 7, Value('xy')), 'xyxJohn'),
|
|
|
|
(RPad('name', 7, Value('xy')), 'Johnxyx'),
|
|
|
|
(LPad('name', 6, Value('x')), 'xxJohn'),
|
|
|
|
(RPad('name', 6, Value('x')), 'Johnxx'),
|
|
|
|
# The default pad string is a space.
|
|
|
|
(LPad('name', 6), ' John'),
|
|
|
|
(RPad('name', 6), 'John '),
|
|
|
|
# If string is longer than length it is truncated.
|
|
|
|
(LPad('name', 2), 'Jo'),
|
|
|
|
(RPad('name', 2), 'Jo'),
|
|
|
|
(LPad('name', 0), ''),
|
|
|
|
(RPad('name', 0), ''),
|
2018-07-01 04:49:20 +08:00
|
|
|
(LPad('name', None), none_value),
|
|
|
|
(RPad('name', None), none_value),
|
|
|
|
(LPad('goes_by', 1), none_value),
|
|
|
|
(RPad('goes_by', 1), none_value),
|
2018-03-20 00:35:16 +08:00
|
|
|
)
|
|
|
|
for function, padded_name in tests:
|
|
|
|
with self.subTest(function=function):
|
|
|
|
authors = Author.objects.annotate(padded_name=function)
|
|
|
|
self.assertQuerysetEqual(authors, [padded_name], lambda a: a.padded_name, ordered=False)
|
|
|
|
|
|
|
|
def test_pad_negative_length(self):
|
|
|
|
for function in (LPad, RPad):
|
|
|
|
with self.subTest(function=function):
|
|
|
|
with self.assertRaisesMessage(ValueError, "'length' must be greater or equal to 0."):
|
|
|
|
function('name', -1)
|
2018-04-04 00:24:04 +08:00
|
|
|
|
|
|
|
def test_combined_with_length(self):
|
|
|
|
Author.objects.create(name='Rhonda', alias='john_smith')
|
|
|
|
Author.objects.create(name='♥♣♠', alias='bytes')
|
2020-06-16 16:01:34 +08:00
|
|
|
authors = Author.objects.annotate(filled=LPad('name', Length('alias')))
|
2018-04-04 00:24:04 +08:00
|
|
|
self.assertQuerysetEqual(
|
|
|
|
authors.order_by('alias'),
|
|
|
|
[' ♥♣♠', ' Rhonda'],
|
|
|
|
lambda a: a.filled,
|
|
|
|
)
|