Skip to content

Commit 176bc54

Browse files
committed
Improved custom object identifier test
This provides an example for implementors and ensures that failing to use the custom class would cause a test failure.
1 parent f5cf421 commit 176bc54

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

test_haystack/core/custom_identifier.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@
22

33
from __future__ import absolute_import, division, print_function, unicode_literals
44

5+
import hashlib
56

67
def get_identifier_method(key):
78
"""
89
Custom get_identifier method used for testing the
910
setting HAYSTACK_IDENTIFIER_MODULE
1011
"""
11-
return key
12+
13+
if hasattr(key, 'get_custom_haystack_id'):
14+
return key.get_custom_haystack_id()
15+
else:
16+
key_bytes = key.encode('utf-8')
17+
return hashlib.md5(key_bytes).hexdigest()

test_haystack/test_utils.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,20 @@ def test_get_identifier(self):
3030

3131
@override_settings(HAYSTACK_IDENTIFIER_METHOD='test_haystack.core.custom_identifier.get_identifier_method')
3232
def test_haystack_identifier_method(self):
33+
# The custom implementation returns the MD-5 hash of the key value by
34+
# default:
3335
get_identifier = _lookup_identifier_method()
34-
self.assertEqual(get_identifier('a.b.c'), 'a.b.c')
36+
self.assertEqual(get_identifier('a.b.c'),
37+
'553f764f7b436175c0387e22b4a19213')
38+
39+
# … but it also supports a custom override mechanism which would
40+
# definitely fail with the default implementation:
41+
class custom_id_class(object):
42+
def get_custom_haystack_id(self):
43+
return 'CUSTOM'
44+
45+
self.assertEqual(get_identifier(custom_id_class()),
46+
'CUSTOM')
3547

3648
@override_settings(HAYSTACK_IDENTIFIER_METHOD='test_haystack.core.custom_identifier.not_there')
3749
def test_haystack_identifier_method_bad_path(self):

0 commit comments

Comments
 (0)