Source

Webware / WebKit / Tests / SessionStoreTest.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import os
import sys
import unittest
from time import time

sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

from MiscUtils import StringIO
from WebKit.SessionStore import SessionStore
from WebKit.SessionMemoryStore import SessionMemoryStore
from WebKit.SessionFileStore import SessionFileStore
from WebKit.SessionDynamicStore import SessionDynamicStore
from WebKit.SessionShelveStore import SessionShelveStore
from WebKit.SessionMemcachedStore import SessionMemcachedStore


class Application(object):
    """Mock application."""

    _sessionDir = 'SessionStoreTestDir'
    _alwaysSaveSessions = True

    def setting(self, key, default=None):
        return dict(
            DynamicSessionTimeout=1,
            MaxDynamicMemorySessions=3,
            MemcachedOnIteration=None,
        ).get(key, default)

    def handleException(self):
        raise Exception('Application Error')


class Session(object):
    """Mock session."""

    _last_expired = None

    def __init__(self, identifier=7, value=None):
        self._identifier = 'foo-%d' % identifier
        self._data = dict(bar=value or identifier*6)
        self._expired = self._dirty = False
        self._timeout = 1800
        self._lastAccessTime = time() - identifier*400
        self._isNew = True

    def identifier(self):
        return self._identifier

    def expiring(self):
        self._expired = True
        Session._last_expired = self._identifier

    def isDirty(self):
        return self._dirty

    def setDirty(self, dirty=True):
        self._dirty = dirty

    def isExpired(self):
        return self._expired

    def timeout(self):
        return self._timeout

    def data(self):
        return self._data

    def bar(self):
        return self._data.get('bar')

    def setBar(self, value):
        self._isNew = False
        self._data['bar'] = value

    def isNew(self):
        return self._isNew

    def lastAccessTime(self):
        return self._lastAccessTime


class SessionStoreTest(unittest.TestCase):

    _storeclass = SessionStore

    _app = Application()

    def setUp(self):
        Session._last_expired = None
        self._store = self._storeclass(self._app)

    def testApplication(self):
        self.assertEqual(self._store.application(), self._app)

    def testEncodeDecode(self):
        session = Session()
        buffer = StringIO()
        self._store.encoder()(session, buffer)
        output = buffer.getvalue()
        buffer.close()
        self.assertTrue(isinstance(output, str))
        buffer = StringIO(output)
        output = self._store.decoder()(buffer)
        buffer.close()
        self.assertTrue(type(output) is type(session))
        self.assertEqual(output._data, session._data)

    def testSetEncoderDecoder(self):
        encoder = lambda obj, f: f.write(str(obj))
        decoder = lambda f: eval(f.read())
        self._store.setEncoderDecoder(encoder, decoder)
        self.assertEqual(self._store.encoder(), encoder)
        self.assertEqual(self._store.decoder(), decoder)


class SessionMemoryStoreTest(SessionStoreTest):

    _storeclass = SessionMemoryStore

    def setUp(self):
        dir = self._app._sessionDir
        if not os.path.exists(dir):
            os.mkdir(dir)
        SessionStoreTest.setUp(self)
        self._store.clear()
        for n in range(7):
            session = Session(n)
            self._store[session.identifier()] = session
            self.assertFalse(session.isExpired())

    def tearDown(self):
        self._store.clear()
        self._store.storeAllSessions()
        dir = self._app._sessionDir
        for filename in os.listdir(dir):
            os.remove(os.path.join(dir, filename))
        os.rmdir(dir)
        SessionStoreTest.tearDown(self)

    def testLen(self):
        self.assertEqual(len(self._store), 7)

    def testGetItem(self):
        store = self._store
        self.assertEqual(self._store['foo-3'].bar(), 18)
        self.assertRaises(KeyError, store.__getitem__, 'foo-7')

    def testSetItem(self):
        session = Session()
        key = session.identifier()
        self._store[key] = session
        self.assertEqual(self._store[key].data(), session.data())

    def testDelItem(self):
        del self._store['foo-3']
        self.assertFalse('foo-3' in self._store)
        self.assertEqual(Session._last_expired, 'foo-3')
        try:
            self._store['foo-3']
        except KeyError:
            pass
        self.assertRaises(KeyError, self._store.__delitem__, 'foo-3')

    def testContains(self):
        store = self._store
        self.assertTrue('foo-0' in store
            and 'foo-3' in store and 'foo-6' in store)
        self.assertFalse('foo' in store)
        self.assertFalse('0' in store or '3' in store or '6' in store)
        self.assertFalse('foo-7' in store)

    def testIter(self):
        keys = set()
        for key in self._store:
            keys.add(key)
        self.assertEqual(keys, set('foo-%d' % n  for n in range(7)))

    def testKeys(self):
        keys = self._store.keys()
        self.assertTrue(isinstance(keys, list))
        self.assertEqual(set(keys), set('foo-%d' % n  for n in range(7)))

    def testClear(self):
        store = self._store
        store.clear()
        self.assertFalse('foo-0' in store
            or 'foo-3' in store or 'foo-6' in store)

    def testSetDefault(self):
        store = self._store
        session = Session()
        self.assertEqual(store.setdefault('foo-3').bar(), 18)
        self.assertEqual(store.setdefault('foo-3', session).bar(), 18)
        self.assertEqual(store.setdefault('foo-7', session).bar(), 42)
        self.assertEqual(store.setdefault('foo-7').bar(), 42)

    def testPop(self):
        store = self._store
        session = self._store['foo-3']
        self.assertFalse(session.isExpired())
        self.assertEqual(store.pop('foo-3').bar(), 18)
        self.assertRaises(KeyError, store.pop, 'foo-3')
        self.assertEqual(store.pop('foo-3', Session()).bar(), 42)
        self.assertRaises(KeyError, store.pop, 'foo-3')
        self.assertFalse(session.isExpired())

    def testGet(self):
        self.assertEqual(self._store.get('foo-4').bar(), 24)
        self.assertEqual(self._store.get('foo-4', Session()).bar(), 24)
        self.assertEqual(self._store.get('foo-7'), None)
        self.assertEqual(self._store.get('foo-7', Session()).bar(), 42)

    def testStoreSession(self):
        session = self._store['foo-3']
        self.assertEqual(session.bar(), 18)
        session.setBar(19)
        self.assertEqual(session.bar(), 19)
        self._store.storeSession(session)
        session = self._store['foo-3']
        self.assertEqual(session.bar(), 19)
        session = Session(3, 20)
        self._store.storeSession(session)
        session = self._store['foo-3']
        self.assertEqual(session.bar(), 20)
        session = Session()
        self._store.storeSession(session)
        session = self._store['foo-7']
        self.assertEqual(session.bar(), 42)

    def testItems(self):
        items = self._store.items()
        self.assertTrue(isinstance(items, list))
        self.assertEqual(len(items), 7)
        self.assertTrue(isinstance(items[4], tuple))
        self.assertEqual(len(items[4]), 2)
        self.assertEqual(dict(items)['foo-3'].bar(), 18)

    def testIterItems(self):
        items = self._store.iteritems()
        self.assertFalse(isinstance(items, list))
        items = list(items)
        self.assertTrue(isinstance(items[4], tuple))
        self.assertEqual(len(items[4]), 2)
        self.assertEqual(dict(items)['foo-3'].bar(), 18)

    def testValues(self):
        values = self._store.values()
        self.assertTrue(isinstance(values, list))
        self.assertEqual(len(values), 7)
        value = values[4]
        self.assertTrue(isinstance(value, Session))
        self.assertEqual(self._store[value.identifier()].bar(), value.bar())

    def testIterValues(self):
        values = self._store.itervalues()
        self.assertFalse(isinstance(values, list))
        values = list(values)
        self.assertEqual(len(values), 7)
        value = values[4]
        self.assertTrue(isinstance(value, Session))
        self.assertEqual(self._store[value.identifier()].bar(), value.bar())

    def testCleanStaleSessions(self):
        store = self._store
        self.assertEqual(len(store), 7)
        self.assertTrue('foo-0' in store and 'foo-4' in store)
        self.assertTrue('foo-5' in store and 'foo-6' in store)
        store.cleanStaleSessions()
        self.assertEqual(len(store), 5)
        self.assertTrue('foo-0' in store and 'foo-4' in store)
        self.assertFalse('foo-5' in store or 'foo-6' in store)


class SessionFileStoreTest(SessionMemoryStoreTest):

    _storeclass = SessionFileStore

    def testMemoryStoreRestoreFiles(self):
        app = self._app
        store = SessionMemoryStore(app)
        self.assertEqual(len(store), 7)
        self.assertTrue('foo-0' in store and 'foo-6' in store)
        store = SessionMemoryStore(app, restoreFiles=False)
        self.assertEqual(len(store), 0)
        self.assertFalse('foo-0' in store or 'foo-6' in store)

    def testFileStoreRestoreFiles(self):
        app = self._app
        store = SessionFileStore(app)
        self.assertEqual(len(store), 7)
        self.assertTrue('foo-0' in store and 'foo-6' in store)
        store = SessionFileStore(app, restoreFiles=False)
        self.assertEqual(len(store), 0)
        self.assertFalse('foo-0' in store or 'foo-6' in store)


class SessionDynamicStoreTest(SessionMemoryStoreTest):

    _storeclass = SessionDynamicStore

    def testCleanStaleSessions(self):
        store = self._store
        memoryStore = store._memoryStore
        fileStore = store._fileStore
        self.assertEqual(len(memoryStore), 7)
        self.assertEqual(len(fileStore), 0)
        SessionMemoryStoreTest.testCleanStaleSessions(self)
        self.assertEqual(len(memoryStore), 3)
        self.assertEqual(len(fileStore), 2)
        self.assertTrue('foo-0' in memoryStore and 'foo-2' in memoryStore)
        self.assertTrue('foo-3' in fileStore and 'foo-4' in fileStore)


class SessionShelveStoreTest(SessionMemoryStoreTest):

    _storeclass = SessionShelveStore

    def testFileShelveRestoreFiles(self):
        app = self._app
        self._store.intervalSweep()
        store = SessionShelveStore(app)
        self.assertEqual(len(store), 7)
        session = store['foo-3']
        self.assertTrue('foo-0' in store and 'foo-6' in store)
        store = SessionShelveStore(app,
            restoreFiles=False, filename='Session.Store2')
        self.assertEqual(len(store), 0)
        self.assertFalse('foo-0' in store or 'foo-6' in store)
        store['foo-3'] = session
        store.storeAllSessions()
        store = SessionShelveStore(app, filename='Session.Store2')
        self.assertEqual(len(store), 1)
        self.assertTrue('foo-3' in store)
        self.assertFalse('foo-0' in store or 'foo-6' in store)


class SessionMemcachedStoreTest(SessionMemoryStoreTest):

    _storeclass = SessionMemcachedStore

    def setUp(self):
        SessionMemoryStoreTest.setUp(self)
        self.setOnIteration()

    def tearDown(self):
        self.setOnIteration()
        SessionMemoryStoreTest.tearDown(self)

    def setOnIteration(self, onIteration=None):
        self._store._onIteration = onIteration

    def testLen(self):
        self.assertEqual(len(self._store), 0)
        self.setOnIteration('Error')
        self.assertRaises(NotImplementedError, len, self._store)

    def testIter(self):
        keys = [key for key in self._store]
        self.assertEqual(keys, [])
        self.setOnIteration('Error')
        keys = lambda:  [key for key in self._store]
        self.assertRaises(NotImplementedError, keys)

    def testKeys(self):
        keys = self._store.keys()
        self.assertEqual(keys, [])
        self.setOnIteration('Error')
        self.assertRaises(NotImplementedError, self._store.keys)

    def testItems(self):
        items = self._store.items()
        self.assertEqual(items, [])
        self.setOnIteration('Error')
        self.assertRaises(NotImplementedError, self._store.items)

    def testIterItems(self):
        items =  [key for key in self._store.iteritems()]
        self.assertEqual(items, [])
        self.setOnIteration('Error')
        items = lambda:  [key for key in self._store.iteritems()]
        self.assertRaises(NotImplementedError, items)

    def testValues(self):
        values = self._store.values()
        self.assertEqual(values, [])
        self.setOnIteration('Error')
        self.assertRaises(NotImplementedError, self._store.values)

    def testIterValues(self):
        values = [key for key in self._store.itervalues()]
        self.assertEqual(values, [])
        self.setOnIteration('Error')
        values = lambda:  [key for key in self._store.values()]
        self.assertRaises(NotImplementedError, values)

    def testClear(self):
        self._store.clear()
        self.setOnIteration('Error')
        self.assertRaises(NotImplementedError, self._store.clear)

    def testCleanStaleSessions(self):
        self._store.cleanStaleSessions()