1 # -*- coding: utf-8 -*-
5 ----------------------------------
7 Tests for `cached-property` module.
10 from time
import sleep
11 from threading
import Lock
, Thread
14 from cached_property
import cached_property
17 class TestCachedProperty(unittest
.TestCase
):
19 def test_cached_property(self
):
28 def add_control(self
):
39 # The control shows that we can continue to add 1.
40 self
.assertEqual(c
.add_control
, 1)
41 self
.assertEqual(c
.add_control
, 2)
43 # The cached version demonstrates how nothing new is added
44 self
.assertEqual(c
.add_cached
, 1)
45 self
.assertEqual(c
.add_cached
, 1)
47 def test_reset_cached_property(self
):
61 # Run standard cache assertion
62 self
.assertEqual(c
.add_cached
, 1)
63 self
.assertEqual(c
.add_cached
, 1)
67 self
.assertEqual(c
.add_cached
, 2)
68 self
.assertEqual(c
.add_cached
, 2)
70 def test_none_cached_property(self
):
83 # Run standard cache assertion
84 self
.assertEqual(c
.add_cached
, None)
87 class TestThreadingIssues(unittest
.TestCase
):
89 def test_threads(self
):
90 """ How well does the standard cached_property implementation work with threads?
91 Short answer: It doesn't! Use threaded_cached_property instead!
101 def add_cached(self
):
103 # Need to guard this since += isn't atomic.
111 for x
in range(num_threads
):
112 thread
= Thread(target
=lambda: c
.add_cached
)
114 threads
.append(thread
)
116 for thread
in threads
:
119 # Threads means that caching is bypassed.
120 self
.assertNotEqual(c
.add_cached
, 1)
122 # This assertion hinges on the fact the system executing the test can
123 # spawn and start running num_threads threads within the sleep period
124 # (defined in the Check class as 1 second). If num_threads were to be
125 # massively increased (try 10000), the actual value returned would be
126 # between 1 and num_threads, depending on thread scheduling and
128 self
.assertEqual(c
.add_cached
, num_threads
)