1. from django.db import connection
    
  2. from django.db.models import CharField
    
  3. from django.db.models.functions import SHA1
    
  4. from django.test import TestCase
    
  5. from django.test.utils import register_lookup
    
  6. 
    
  7. from ..models import Author
    
  8. 
    
  9. 
    
  10. class SHA1Tests(TestCase):
    
  11.     @classmethod
    
  12.     def setUpTestData(cls):
    
  13.         Author.objects.bulk_create(
    
  14.             [
    
  15.                 Author(alias="John Smith"),
    
  16.                 Author(alias="Jordan Élena"),
    
  17.                 Author(alias="皇帝"),
    
  18.                 Author(alias=""),
    
  19.                 Author(alias=None),
    
  20.             ]
    
  21.         )
    
  22. 
    
  23.     def test_basic(self):
    
  24.         authors = (
    
  25.             Author.objects.annotate(
    
  26.                 sha1_alias=SHA1("alias"),
    
  27.             )
    
  28.             .values_list("sha1_alias", flat=True)
    
  29.             .order_by("pk")
    
  30.         )
    
  31.         self.assertSequenceEqual(
    
  32.             authors,
    
  33.             [
    
  34.                 "e61a3587b3f7a142b8c7b9263c82f8119398ecb7",
    
  35.                 "0781e0745a2503e6ded05ed5bc554c421d781b0c",
    
  36.                 "198d15ea139de04060caf95bc3e0ec5883cba881",
    
  37.                 "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    
  38.                 "da39a3ee5e6b4b0d3255bfef95601890afd80709"
    
  39.                 if connection.features.interprets_empty_strings_as_nulls
    
  40.                 else None,
    
  41.             ],
    
  42.         )
    
  43. 
    
  44.     def test_transform(self):
    
  45.         with register_lookup(CharField, SHA1):
    
  46.             authors = Author.objects.filter(
    
  47.                 alias__sha1="e61a3587b3f7a142b8c7b9263c82f8119398ecb7",
    
  48.             ).values_list("alias", flat=True)
    
  49.             self.assertSequenceEqual(authors, ["John Smith"])