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.                     if connection.features.interprets_empty_strings_as_nulls
    
  28.                     else None,
    
  29.                 ),
    
  30.             ],
    
  31.         )
    
  32. 
    
  33.     def test_null_argument(self):
    
  34.         authors = Author.objects.annotate(
    
  35.             nullif=NullIf("name", Value(None))
    
  36.         ).values_list("nullif")
    
  37.         self.assertCountEqual(authors, [("John Smith",), ("Rhonda",)])
    
  38. 
    
  39.     def test_too_few_args(self):
    
  40.         msg = "'NullIf' takes exactly 2 arguments (1 given)"
    
  41.         with self.assertRaisesMessage(TypeError, msg):
    
  42.             NullIf("name")
    
  43. 
    
  44.     @skipUnless(connection.vendor == "oracle", "Oracle specific test for NULL-literal")
    
  45.     def test_null_literal(self):
    
  46.         msg = "Oracle does not allow Value(None) for expression1."
    
  47.         with self.assertRaisesMessage(ValueError, msg):
    
  48.             list(
    
  49.                 Author.objects.annotate(nullif=NullIf(Value(None), "name")).values_list(
    
  50.                     "nullif"
    
  51.                 )
    
  52.             )