| 1 |
from unittest import skipUnless |
| 2 |
|
| 3 |
from django.db import connection |
| 4 |
from django.db.models import Value |
| 5 |
from django.db.models.functions import NullIf |
| 6 |
from django.test import TestCase |
| 7 |
|
| 8 |
from ..models import Author |
| 9 |
|
| 10 |
|
| 11 |
class NullIfTests(TestCase): |
| 12 |
@classmethod |
| 13 |
def setUpTestData(cls): |
| 14 |
Author.objects.create(name="John Smith", alias="smithj") |
| 15 |
Author.objects.create(name="Rhonda", alias="Rhonda") |
| 16 |
|
| 17 |
def test_basic(self): |
| 18 |
authors = Author.objects.annotate(nullif=NullIf("alias", "name")).values_list( |
| 19 |
"nullif" |
| 20 |
) |
| 21 |
self.assertCountEqual( |
| 22 |
authors, |
| 23 |
[ |
| 24 |
("smithj",), |
| 25 |
( |
| 26 |
( |
| 27 |
"" |
| 28 |
if connection.features.interprets_empty_strings_as_nulls |
| 29 |
else None |
| 30 |
), |
| 31 |
), |
| 32 |
], |
| 33 |
) |
| 34 |
|
| 35 |
def test_null_argument(self): |
| 36 |
authors = Author.objects.annotate( |
| 37 |
nullif=NullIf("name", Value(None)) |
| 38 |
).values_list("nullif") |
| 39 |
self.assertCountEqual(authors, [("John Smith",), ("Rhonda",)]) |
| 40 |
|
| 41 |
def test_too_few_args(self): |
| 42 |
msg = "'NullIf' takes exactly 2 arguments (1 given)" |
| 43 |
with self.assertRaisesMessage(TypeError, msg): |
| 44 |
NullIf("name") |
| 45 |
|
| 46 |
@skipUnless(connection.vendor == "oracle", "Oracle specific test for NULL-literal") |
| 47 |
def test_null_literal(self): |
| 48 |
msg = "Oracle does not allow Value(None) for expression1." |
| 49 |
with self.assertRaisesMessage(ValueError, msg): |
| 50 |
list( |
| 51 |
Author.objects.annotate(nullif=NullIf(Value(None), "name")).values_list( |
| 52 |
"nullif" |
| 53 |
) |
| 54 |
) |