Debian Codegraph @

tests/test_managers/base.py

raw symbols SCIP
1 # coding: utf-8
2 import threading
3 import unittest
4
5 import time
6
7 import datetime
8
9 from beaker.cache import Cache
10 from beaker.middleware import SessionMiddleware, CacheMiddleware
11 from webtest import TestApp as WebTestApp
12
13 class CacheManagerBaseTests(unittest.TestCase):
14 SUPPORTS_EXPIRATION = True
15 SUPPORTS_TIMEOUT = True
16 CACHE_ARGS = {}
17
18 @classmethod
19 def setUpClass(cls):
20 def simple_session_app(environ, start_response):
21 session = environ['beaker.session']
22 sess_id = environ.get('SESSION_ID')
23 if environ['PATH_INFO'].startswith('/invalid'):
24 # Attempt to access the session
25 id = session.id
26 session['value'] = 2
27 else:
28 if sess_id:
29 session = session.get_by_id(sess_id)
30 if not session:
31 start_response('200 OK', [('Content-type', 'text/plain')])
32 return [("No session id of %s found." % sess_id).encode('utf-8')]
33 if 'value' not in session:
34 session['value'] = 0
35 session['value'] += 1
36 if not environ['PATH_INFO'].startswith('/nosave'):
37 session.save()
38 start_response('200 OK', [('Content-type', 'text/plain')])
39 return [('The current value is: %d, session id is %s' % (session['value'],
40 session.id)).encode('utf-8')]
41
42 def simple_app(environ, start_response):
43 extra_args = cls.CACHE_ARGS
44 clear = False
45 if environ.get('beaker.clear'):
46 clear = True
47 cache = environ['beaker.cache'].get_cache('testcache', **extra_args)
48 if clear:
49 cache.clear()
50 try:
51 value = cache.get_value('value')
52 except:
53 value = 0
54 cache.set_value('value', value + 1)
55 start_response('200 OK', [('Content-type', 'text/plain')])
56 return [('The current value is: %s' % cache.get_value('value')).encode('utf-8')]
57
58 def using_none_app(environ, start_response):
59 extra_args = cls.CACHE_ARGS
60 clear = False
61 if environ.get('beaker.clear'):
62 clear = True
63 cache = environ['beaker.cache'].get_cache('testcache', **extra_args)
64 if clear:
65 cache.clear()
66 try:
67 value = cache.get_value('value')
68 except:
69 value = 10
70 cache.set_value('value', None)
71 start_response('200 OK', [('Content-type', 'text/plain')])
72 return [('The current value is: %s' % value).encode('utf-8')]
73
74 def cache_manager_app(environ, start_response):
75 cm = environ['beaker.cache']
76 cm.get_cache('test')['test_key'] = 'test value'
77
78 start_response('200 OK', [('Content-type', 'text/plain')])
79 yield ("test_key is: %s\n" % cm.get_cache('test')['test_key']).encode('utf-8')
80 cm.get_cache('test').clear()
81
82 try:
83 test_value = cm.get_cache('test')['test_key']
84 except KeyError:
85 yield "test_key cleared".encode('utf-8')
86 else:
87 yield (
88 "test_key wasn't cleared, is: %s\n" % cm.get_cache('test')['test_key']
89 ).encode('utf-8')
90
91 cls.simple_session_app = staticmethod(simple_session_app)
92 cls.simple_app = staticmethod(simple_app)
93 cls.using_none_app = staticmethod(using_none_app)
94 cls.cache_manager_app = staticmethod(cache_manager_app)
95
96 def setUp(self):
97 Cache('test', **self.CACHE_ARGS).clear()
98
99 def test_session(self):
100 app = WebTestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS))
101 res = app.get('/')
102 assert 'current value is: 1' in res
103 res = app.get('/')
104 assert 'current value is: 2' in res
105 res = app.get('/')
106 assert 'current value is: 3' in res
107
108 def test_session_invalid(self):
109 app = WebTestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS))
110 res = app.get('/invalid', headers=dict(
111 Cookie='beaker.session.id=df7324911e246b70b5781c3c58328442; Path=/'))
112 assert 'current value is: 2' in res
113
114 def test_session_timeout(self):
115 app = WebTestApp(SessionMiddleware(self.simple_session_app, timeout=1, **self.CACHE_ARGS))
116
117 session = app.app._get_session()
118 session.save()
119 if self.SUPPORTS_TIMEOUT:
120 assert session.namespace.timeout == 121
121
122 res = app.get('/')
123 assert 'current value is: 1' in res
124 res = app.get('/')
125 assert 'current value is: 2' in res
126 res = app.get('/')
127 assert 'current value is: 3' in res
128
129 def test_has_key(self):
130 cache = Cache('test', **self.CACHE_ARGS)
131 o = object()
132 cache.set_value("test", o)
133 assert "test" in cache
134 assert "foo" not in cache
135 cache.remove_value("test")
136 assert "test" not in cache
137
138 def test_clear(self):
139 cache = Cache('test', **self.CACHE_ARGS)
140 cache.set_value('test', 20)
141 cache.set_value('fred', 10)
142 assert 'test' in cache
143 assert 'fred' in cache
144 cache.clear()
145 assert "test" not in cache
146
147 def test_has_key_multicache(self):
148 cache = Cache('test', **self.CACHE_ARGS)
149 o = object()
150 cache.set_value("test", o)
151 assert "test" in cache
152 cache = Cache('test', **self.CACHE_ARGS)
153 assert "test" in cache
154
155 def test_unicode_keys(self):
156 cache = Cache('test', **self.CACHE_ARGS)
157 o = object()
158 cache.set_value('hiŏ', o)
159 assert 'hiŏ' in cache
160 assert 'hŏa' not in cache
161 cache.remove_value('hiŏ')
162 assert 'hiŏ' not in cache
163
164 def test_long_unicode_keys(self):
165 cache = Cache('test', **self.CACHE_ARGS)
166 o = object()
167 long_str = (
168 'Очень длинная строка, которая не влезает в сто двадцать восемь байт и поэтому не проходит ограничение в check_key, что очень прискорбно, не правда ли, друзья? Давайте же скорее исправим это досадное недоразумение!'
169 )
170 cache.set_value(long_str, o)
171 assert long_str in cache
172 cache.remove_value(long_str)
173 assert long_str not in cache
174
175 def test_spaces_in_unicode_keys(self):
176 cache = Cache('test', **self.CACHE_ARGS)
177 o = object()
178 cache.set_value('hi ŏ', o)
179 assert 'hi ŏ' in cache
180 assert 'hŏa' not in cache
181 cache.remove_value('hi ŏ')
182 assert 'hi ŏ' not in cache
183
184 def test_spaces_in_keys(self):
185 cache = Cache('test', **self.CACHE_ARGS)
186 cache.set_value("has space", 24)
187 assert "has space" in cache
188 assert 24 == cache.get_value("has space")
189 cache.set_value("hasspace", 42)
190 assert "hasspace" in cache
191 assert 42 == cache.get_value("hasspace")
192
193 def test_increment(self):
194 app = WebTestApp(CacheMiddleware(self.simple_app))
195 res = app.get('/', extra_environ={'beaker.clear': True})
196 assert 'current value is: 1' in res
197 res = app.get('/')
198 assert 'current value is: 2' in res
199 res = app.get('/')
200 assert 'current value is: 3' in res
201
202 app = WebTestApp(CacheMiddleware(self.simple_app))
203 res = app.get('/', extra_environ={'beaker.clear': True})
204 assert 'current value is: 1' in res
205 res = app.get('/')
206 assert 'current value is: 2' in res
207 res = app.get('/')
208 assert 'current value is: 3' in res
209
210 def test_cache_manager(self):
211 app = WebTestApp(CacheMiddleware(self.cache_manager_app))
212 res = app.get('/')
213 assert 'test_key is: test value' in res
214 assert 'test_key cleared' in res
215
216 def test_store_none(self):
217 app = WebTestApp(CacheMiddleware(self.using_none_app))
218 res = app.get('/', extra_environ={'beaker.clear': True})
219 assert 'current value is: 10' in res
220 res = app.get('/')
221 assert 'current value is: None' in res
222
223 def test_expiretime(self):
224 cache = Cache('test', **self.CACHE_ARGS)
225 cache.set_value("has space", 24, expiretime=1)
226 assert "has space" in cache
227 time.sleep(1.1)
228 assert "has space" not in cache
229
230 def test_expiretime_automatic(self):
231 if not self.SUPPORTS_EXPIRATION:
232 self.skipTest('NamespaceManager does not support automatic expiration')
233
234 cache = Cache('test', **self.CACHE_ARGS)
235 cache.set_value("has space", 24, expiretime=1)
236 assert "has space" in cache
237 time.sleep(1.1)
238 assert "has space" not in cache
239
240 def test_createfunc(self):
241 cache = Cache('test', **self.CACHE_ARGS)
242
243 def createfunc():
244 createfunc.count += 1
245 return createfunc.count
246 createfunc.count = 0
247
248 def keepitlocked():
249 lock = cache.namespace.get_creation_lock('test')
250 lock.acquire()
251 keepitlocked.acquired = True
252 time.sleep(1.0)
253 lock.release()
254 keepitlocked.acquired = False
255
256 v0 = cache.get_value('test', createfunc=createfunc)
257 self.assertEqual(v0, 1)
258
259 v0 = cache.get_value('test', createfunc=createfunc)
260 self.assertEqual(v0, 1)
261
262 cache.remove_value('test')
263
264 begin = datetime.datetime.utcnow()
265 t = threading.Thread(target=keepitlocked)
266 t.start()
267 while not keepitlocked.acquired:
268 # Wait for the thread that should lock the cache to start.
269 time.sleep(0.001)
270
271 v0 = cache.get_value('test', createfunc=createfunc)
272 self.assertEqual(v0, 2)
273
274 # Ensure that the `get_value` was blocked by the concurrent thread.
275 assert datetime.datetime.utcnow() - begin > datetime.timedelta(seconds=1)
276
277 t.join()