Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added tests for pymongo, only on py2.

  • Loading branch information...
commit dd00894a8318f875be28640d5dce2a637fe6ed6f 1 parent f02063a
@mmerickel mmerickel authored
View
77 anykeystore/backends/mongodb.py
@@ -0,0 +1,77 @@
+from datetime import datetime
+
+from pymongo import Connection
+from pymongo.binary import Binary
+
+from anykeystore.compat import pickle
+from anykeystore.interfaces import KeyValueStore
+from anykeystore.utils import coerce_timedelta
+
+
+class MongoDBStore(KeyValueStore):
+ """ Simple storage via SQLAlchemy.
+
+ :param db: The name of the mongo database.
+ :param collection: Optional (default="key_storage").
+ The document collection within the database.
+ :param host: MongoDB server host.
+ :param port: MongoDB server port.
+ """
+
+ def __init__(self,
+ db,
+ collection='key_storage',
+ host='localhost',
+ port=27017):
+ self.host = host
+ self.port = int(port)
+ self.db = db
+ self.collection = collection
+
+ def _get_conn(self):
+ db_conn = Connection(self.host, self.port, slave_okay=False)
+ conn = db_conn[self.db]
+ #Set arbitrary limit on how large user_store session can grow to
+ #http://www.mongodb.org/display/DOCS/Capped+Collections
+ if not self.collection in conn.collection_names(): # pragma: no cover
+ conn.create_collection(self.collection)
+ return conn
+
+ def retrieve(self, key):
+ c = self._get_conn()
+ data = c[self.collection].find_one({'key': key})
+ if data:
+ expires = data['expires']
+ if expires is None or datetime.utcnow() < expires:
+ return pickle.loads(data['value'])
+ raise KeyError
+
+ def store(self, key, value, expires=None):
+ expiration = None
+ if expires:
+ expiration = datetime.utcnow() + coerce_timedelta(expires)
+ c = self._get_conn()
+ c[self.collection].update(
+ {'key': key},
+ {
+ '$set': {
+ 'value': Binary(pickle.dumps(value)),
+ 'expires': expiration,
+ },
+ },
+ upsert=True,
+ safe=True,
+ )
+
+ def delete(self, key):
+ c = self._get_conn()
+ c[self.collection].remove({'key': key}, safe=True)
+
+ def purge_expired(self):
+ c = self._get_conn()
+ c[self.collection].remove(
+ {'expires': {'$lte': datetime.utcnow()}},
+ safe=True,
+ )
+
+backend = MongoDBStore
View
37 anykeystore/tests/test_backends/test_mongodb.py
@@ -0,0 +1,37 @@
+import unittest2 as unittest
+
+def setUpModule():
+ try: # pragma: no cover
+ import pymongo
+ except ImportError: # pragma: no cover
+ raise unittest.SkipTest('must install pymongo to run mongodb tests')
+
+class TestMongoStore(unittest.TestCase):
+
+ def _makeOne(self):
+ from anykeystore.backends.mongodb import MongoDBStore
+ store = MongoDBStore(db='test', collection='test_store')
+ return store
+
+ def test_it(self):
+ store = self._makeOne()
+ store.store('foo', 'bar')
+ value = store.retrieve('foo')
+ self.assertEqual(value, 'bar')
+
+ def test_it_delete(self):
+ store = self._makeOne()
+ store.store('foo', 'bar')
+ store.delete('foo')
+ self.assertRaises(KeyError, store.retrieve, 'foo')
+
+ def test_it_old(self):
+ store = self._makeOne()
+ store.store('foo', 'bar', expires=-1)
+ self.assertRaises(KeyError, store.retrieve, 'foo')
+
+ def test_it_purge(self):
+ store = self._makeOne()
+ store.store('foo', 'bar', expires=-1)
+ store.purge_expired()
+ self.assertRaises(KeyError, store.retrieve, 'foo')
View
19 setup.py
@@ -1,6 +1,17 @@
from setuptools import setup, find_packages
import sys, os
+py_version = sys.version_info[:2]
+
+PY3 = py_version[0] == 3
+
+if PY3:
+ if py_version < (3, 2):
+ raise RuntimeError('On Python 3, Pyramid requires Python 3.2 or better')
+else:
+ if py_version < (2, 6):
+ raise RuntimeError('On Python 2, Pyramid requires Python 2.6 or better')
+
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
@@ -10,6 +21,13 @@
requires = []
+tests_require = requires + []
+
+if PY3:
+ tests_require.append('unittest2py3k')
+else:
+ tests_require.append('unittest2')
+
setup(
name='anykeystore',
version='0.1a2',
@@ -34,6 +52,7 @@
include_package_data=True,
zip_safe=False,
install_requires=requires,
+ tests_require=tests_require,
test_suite="anykeystore.tests",
entry_points="""\
""",
View
8 tox.ini
@@ -7,6 +7,13 @@ commands =
python setup.py test -q
deps =
sqlalchemy
+ pymongo
+
+[testenv:py32]
+commands =
+ python setup.py test -q
+deps =
+ sqlalchemy
[testenv:cover]
basepython =
@@ -18,6 +25,7 @@ deps =
coverage
nosexcover
sqlalchemy
+ pymongo
# we separate coverage into its own testenv because a) "last run wins" wrt
# cobertura jenkins reporting and b) pypy and jython can't handle any
Please sign in to comment.
Something went wrong with that request. Please try again.