|
1 import unittest |
|
2 |
|
3 import django.utils.copycompat as copy |
|
4 from django.utils.functional import SimpleLazyObject |
|
5 |
|
6 class _ComplexObject(object): |
|
7 def __init__(self, name): |
|
8 self.name = name |
|
9 |
|
10 def __eq__(self, other): |
|
11 return self.name == other.name |
|
12 |
|
13 def __hash__(self): |
|
14 return hash(self.name) |
|
15 |
|
16 def __str__(self): |
|
17 return "I am _ComplexObject(%r)" % self.name |
|
18 |
|
19 def __unicode__(self): |
|
20 return unicode(self.name) |
|
21 |
|
22 def __repr__(self): |
|
23 return "_ComplexObject(%r)" % self.name |
|
24 |
|
25 complex_object = lambda: _ComplexObject("joe") |
|
26 |
|
27 class TestUtilsSimpleLazyObject(unittest.TestCase): |
|
28 """ |
|
29 Tests for SimpleLazyObject |
|
30 """ |
|
31 # Note that concrete use cases for SimpleLazyObject are also found in the |
|
32 # auth context processor tests (unless the implementation of that function |
|
33 # is changed). |
|
34 |
|
35 def test_equality(self): |
|
36 self.assertEqual(complex_object(), SimpleLazyObject(complex_object)) |
|
37 self.assertEqual(SimpleLazyObject(complex_object), complex_object()) |
|
38 |
|
39 def test_hash(self): |
|
40 # hash() equality would not be true for many objects, but it should be |
|
41 # for _ComplexObject |
|
42 self.assertEqual(hash(complex_object()), |
|
43 hash(SimpleLazyObject(complex_object))) |
|
44 |
|
45 def test_repr(self): |
|
46 # For debugging, it will really confuse things if there is no clue that |
|
47 # SimpleLazyObject is actually a proxy object. So we don't |
|
48 # proxy __repr__ |
|
49 self.assert_("SimpleLazyObject" in repr(SimpleLazyObject(complex_object))) |
|
50 |
|
51 def test_str(self): |
|
52 self.assertEqual("I am _ComplexObject('joe')", str(SimpleLazyObject(complex_object))) |
|
53 |
|
54 def test_unicode(self): |
|
55 self.assertEqual(u"joe", unicode(SimpleLazyObject(complex_object))) |
|
56 |
|
57 def test_class(self): |
|
58 # This is important for classes that use __class__ in things like |
|
59 # equality tests. |
|
60 self.assertEqual(_ComplexObject, SimpleLazyObject(complex_object).__class__) |
|
61 |
|
62 def test_deepcopy(self): |
|
63 # Check that we *can* do deep copy, and that it returns the right |
|
64 # objects. |
|
65 |
|
66 # First, for an unevaluated SimpleLazyObject |
|
67 s = SimpleLazyObject(complex_object) |
|
68 assert s._wrapped is None |
|
69 s2 = copy.deepcopy(s) |
|
70 assert s._wrapped is None # something has gone wrong is s is evaluated |
|
71 self.assertEqual(s2, complex_object()) |
|
72 |
|
73 # Second, for an evaluated SimpleLazyObject |
|
74 name = s.name # evaluate |
|
75 assert s._wrapped is not None |
|
76 s3 = copy.deepcopy(s) |
|
77 self.assertEqual(s3, complex_object()) |