From b625907a79bb1336cbc54231bdf7cace25fecaf7 Mon Sep 17 00:00:00 2001 From: Brad Melin Date: Tue, 21 Feb 2017 08:43:38 +0200 Subject: Fixed #27834 -- Added StrIndex database function. --- tests/db_functions/test_strindex.py | 65 +++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 tests/db_functions/test_strindex.py (limited to 'tests') diff --git a/tests/db_functions/test_strindex.py b/tests/db_functions/test_strindex.py new file mode 100644 index 0000000000..c516d2d2ab --- /dev/null +++ b/tests/db_functions/test_strindex.py @@ -0,0 +1,65 @@ +from django.db.models.functions import StrIndex +from django.test import TestCase +from django.utils import timezone + +from .models import Article, Author + + +class StrIndexTests(TestCase): + def test_annotate_charfield(self): + Author.objects.create(name='George. R. R. Martin') + Author.objects.create(name='J. R. R. Tolkien') + Author.objects.create(name='Terry Pratchett') + authors = Author.objects.annotate(fullstop=StrIndex('name', 'R.')) + self.assertQuerysetEqual(authors.order_by('name'), [9, 4, 0], lambda a: a.fullstop) + + def test_annotate_textfield(self): + Article.objects.create( + title='How to Django', + text='Lorem ipsum dolor sit amet.', + written=timezone.now(), + ) + Article.objects.create( + title='How to Tango', + text="Won't find anything here.", + written=timezone.now(), + ) + articles = Article.objects.annotate(ipsum_index=StrIndex('text', 'ipsum')) + self.assertQuerysetEqual(articles.order_by('title'), [7, 0], lambda a: a.ipsum_index) + + def test_order_by(self): + Author.objects.create(name='Terry Pratchett') + Author.objects.create(name='J. R. R. Tolkien') + Author.objects.create(name='George. R. R. Martin') + self.assertQuerysetEqual( + Author.objects.order_by(StrIndex('name', 'R.').asc()), [ + 'Terry Pratchett', + 'J. R. R. Tolkien', + 'George. R. R. Martin', + ], + lambda a: a.name + ) + self.assertQuerysetEqual( + Author.objects.order_by(StrIndex('name', 'R.').desc()), [ + 'George. R. R. Martin', + 'J. R. R. Tolkien', + 'Terry Pratchett', + ], + lambda a: a.name + ) + + def test_unicode_values(self): + Author.objects.create(name='ツリー') + Author.objects.create(name='皇帝') + Author.objects.create(name='皇帝 ツリー') + authors = Author.objects.annotate(sb=StrIndex('name', 'リ')) + self.assertQuerysetEqual(authors.order_by('name'), [2, 0, 5], lambda a: a.sb) + + def test_filtering(self): + Author.objects.create(name='George. R. R. Martin') + Author.objects.create(name='Terry Pratchett') + self.assertQuerysetEqual( + Author.objects.annotate(middle_name=StrIndex('name', 'R.')).filter(middle_name__gt=0), + ['George. R. R. Martin'], + lambda a: a.name + ) -- cgit v1.3