| 1 |
from django.db import connection |
| 2 |
|
| 3 |
from . import PostgreSQLTestCase |
| 4 |
from .models import CharFieldModel, TextFieldModel |
| 5 |
|
| 6 |
|
| 7 |
class UnaccentTest(PostgreSQLTestCase): |
| 8 |
Model = CharFieldModel |
| 9 |
|
| 10 |
@classmethod |
| 11 |
def setUpTestData(cls): |
| 12 |
cls.Model.objects.bulk_create( |
| 13 |
[ |
| 14 |
cls.Model(field="àéÖ"), |
| 15 |
cls.Model(field="aeO"), |
| 16 |
cls.Model(field="aeo"), |
| 17 |
] |
| 18 |
) |
| 19 |
|
| 20 |
def test_unaccent(self): |
| 21 |
self.assertQuerySetEqual( |
| 22 |
self.Model.objects.filter(field__unaccent="aeO"), |
| 23 |
["àéÖ", "aeO"], |
| 24 |
transform=lambda instance: instance.field, |
| 25 |
ordered=False, |
| 26 |
) |
| 27 |
|
| 28 |
def test_unaccent_chained(self): |
| 29 |
""" |
| 30 |
Unaccent can be used chained with a lookup (which should be the case |
| 31 |
since unaccent implements the Transform API) |
| 32 |
""" |
| 33 |
self.assertQuerySetEqual( |
| 34 |
self.Model.objects.filter(field__unaccent__iexact="aeO"), |
| 35 |
["àéÖ", "aeO", "aeo"], |
| 36 |
transform=lambda instance: instance.field, |
| 37 |
ordered=False, |
| 38 |
) |
| 39 |
self.assertQuerySetEqual( |
| 40 |
self.Model.objects.filter(field__unaccent__endswith="éÖ"), |
| 41 |
["àéÖ", "aeO"], |
| 42 |
transform=lambda instance: instance.field, |
| 43 |
ordered=False, |
| 44 |
) |
| 45 |
|
| 46 |
def test_unaccent_with_conforming_strings_off(self): |
| 47 |
"""SQL is valid when standard_conforming_strings is off.""" |
| 48 |
with connection.cursor() as cursor: |
| 49 |
cursor.execute("SHOW standard_conforming_strings") |
| 50 |
disable_conforming_strings = cursor.fetchall()[0][0] == "on" |
| 51 |
if disable_conforming_strings: |
| 52 |
cursor.execute("SET standard_conforming_strings TO off") |
| 53 |
try: |
| 54 |
self.assertQuerySetEqual( |
| 55 |
self.Model.objects.filter(field__unaccent__endswith="éÖ"), |
| 56 |
["àéÖ", "aeO"], |
| 57 |
transform=lambda instance: instance.field, |
| 58 |
ordered=False, |
| 59 |
) |
| 60 |
finally: |
| 61 |
if disable_conforming_strings: |
| 62 |
cursor.execute("SET standard_conforming_strings TO on") |
| 63 |
|
| 64 |
def test_unaccent_accentuated_needle(self): |
| 65 |
self.assertQuerySetEqual( |
| 66 |
self.Model.objects.filter(field__unaccent="aéÖ"), |
| 67 |
["àéÖ", "aeO"], |
| 68 |
transform=lambda instance: instance.field, |
| 69 |
ordered=False, |
| 70 |
) |
| 71 |
|
| 72 |
|
| 73 |
class UnaccentTextFieldTest(UnaccentTest): |
| 74 |
""" |
| 75 |
TextField should have the exact same behavior as CharField |
| 76 |
regarding unaccent lookups. |
| 77 |
""" |
| 78 |
|
| 79 |
Model = TextFieldModel |