Source

Dragoman / dragoman / lib / test / test_httpcache.py

import os
import py.test
from dragoman.lib import httpcache
from dingus import DontCare, returner, Dingus
from dragoman.lib.testing import DingusTestCase, mock, restore
from hashlib import md5

__here__ = os.path.dirname(os.path.abspath(__file__))

class TestHttpCache(DingusTestCase(httpcache.BsddbCache)):
	def test_init(self):
		cache = httpcache.BsddbCache('foo')
		assert cache.safe
		assert httpcache.bsddb.calls('btopen', ('foo'))

	def test_get(self):
		safe = Dingus(return_value='safe foo')
		cache = httpcache.BsddbCache('foo', safe=safe)
		result = cache.get('bar')
		assert safe.calls('()', ('bar'))
		assert cache.db.calls('has_key', ('safe foo'))
		assert cache.db.calls('__getitem__', ('safe foo'))

	def test_set(self):
		safe = Dingus(return_value='safe bar')
		cache = httpcache.BsddbCache('foo', safe=safe)
		cache.set('bar', 'baz')
		args = ('safe bar', 'baz')
		assert cache.db.calls('__setitem__').once().args == args
		assert cache.db.calls('sync')

	def test_delete(self):
		safe = Dingus(return_value='safe bar')
		cache = httpcache.BsddbCache('foo', safe=safe)
		cache.delete('bar')
		assert cache.db.calls('has_key', ('safe bar'))
		# force an explicit __delitem__ call instead of del db[key]
		assert cache.db.calls('__delitem__', ('safe bar'))
		assert cache.db.calls('sync')
		

class TestHttpCacheBsdDB(object):
	def setup_class(self):
		dbfile = os.path.join(__here__, 'httpcache.db')
		if os.path.exists(dbfile):
			os.remove(dbfile)
		self.cache = httpcache.BsddbCache(dbfile)

	def safe(self, key):
		return '%s,%s' % (key, md5(key).hexdigest())

	def test_add_to_cache(self):
		k, v = 'foo', 'bar'
		self.cache.set(k, v)
		assert not self.cache.db.has_key(k)
		assert self.cache.db[self.safe(k)] == v

	def test_get_from_cache(self):
		k, v = 'foo', 'baz'
		self.cache.db[self.safe(k)] = v
		assert self.cache.get(k) == v

	def test_remove_from_cache(self):
		k, v = 'foo', 'bee'
		self.cache.set(k, v)
		assert self.cache.get(k) == v
		self.cache.delete(k)
		assert self.cache.get(k) == None