Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add tests for app init with mongokit and authentication

  • Loading branch information...
commit 3b58cba13ba1580ce4fb1c551b4e6cf27e8b6537 1 parent e6084b8
@jarus authored
Showing with 112 additions and 10 deletions.
  1. +20 −9 flask_mongokit.py
  2. +92 −1 tests.py
View
29 flask_mongokit.py
@@ -18,12 +18,15 @@
from werkzeug.routing import BaseConverter
from flask import abort, _request_ctx_stack
-try:
+try: # pragma: no cover
from flask import _app_ctx_stack
ctx_stack = _app_ctx_stack
-except ImportError:
+except ImportError: # pragma: no cover
ctx_stack = _request_ctx_stack
+class AuthenticationIncorrect(Exception):
+ pass
+
class BSONObjectIdConverter(BaseConverter):
"""A simple converter for the RESTfull URL routing system of Flask.
@@ -118,18 +121,19 @@ def init_app(self, app):
app.config.setdefault('MONGODB_PASSWORD', None)
# 0.9 and later
- if hasattr(app, 'teardown_appcontext'):
+ # no coverage check because there is everytime only one
+ if hasattr(app, 'teardown_appcontext'): # pragma: no cover
app.teardown_appcontext(self._teardown_request)
# 0.7 to 0.8
- elif hasattr(app, 'teardown_request'):
+ elif hasattr(app, 'teardown_request'): # pragma: no cover
app.teardown_request(self._teardown_request)
# Older Flask versions
- else:
+ else: # pragma: no cover
app.after_request(self._teardown_request)
- # # register extension with app
- # app.extensions = getattr(app, 'extensions', {})
- # app.extensions['mongokit'] = self
+ # register extension with app only to say "I'm here"
+ app.extensions = getattr(app, 'extensions', {})
+ app.extensions['mongokit'] = self
app.url_map.converters['ObjectId'] = BSONObjectIdConverter
@@ -180,6 +184,11 @@ def connect(self):
``MONGODB_PASSWORD`` then you will be authenticated at the
``MONGODB_DATABASE``.
"""
+ if self.app is None:
+ raise RuntimeError('The flask-mongokit extension was not init to '
+ 'the current application. Please make sure '
+ 'to call init_app() first.')
+
ctx = ctx_stack.top
mongokit_connection = getattr(ctx, 'mongokit_connection', None)
if mongokit_connection is None:
@@ -199,10 +208,12 @@ def connect(self):
)
if ctx.app.config.get('MONGODB_USERNAME') is not None:
- ctx.mongokit_db.authenticate(
+ auth_success = ctx.mongokit_database.authenticate(
ctx.app.config.get('MONGODB_USERNAME'),
ctx.app.config.get('MONGODB_PASSWORD')
)
+ if not auth_success:
+ raise AuthenticationIncorrect
@property
def connected(self):
View
93 tests.py
@@ -7,9 +7,10 @@
from flask import Flask
from flask_mongokit import MongoKit, BSONObjectIdConverter, \
- Document, Collection
+ Document, Collection, AuthenticationIncorrect
from werkzeug.exceptions import BadRequest, NotFound
from bson import ObjectId
+from pymongo import Connection
class BlogPost(Document):
__collection__ = "posts"
@@ -68,6 +69,27 @@ def test_bson_object_id_converter(self):
assert converter.to_url(ObjectId("4e4ac5cfffc84958fa1f45fb")) == \
"4e4ac5cfffc84958fa1f45fb"
+ def test_is_extension_registerd(self):
+ assert hasattr(self.app, 'extensions')
+ assert 'mongokit' in self.app.extensions
+ assert self.app.extensions['mongokit'] == self.db
+
+class BaseTestCaseInitAppWithContext():
+ def setUp(self):
+ self.app = create_app()
+
+ def test_init_later(self):
+ self.db = MongoKit()
+ self.assertRaises(RuntimeError, self.db.connect)
+
+ self.db.init_app(self.app)
+ self.db.connect()
+ assert self.db.connected
+
+ def test_init_immediately(self):
+ self.db = MongoKit(self.app)
+ self.db.connect()
+ assert self.db.connected
class BaseTestCaseWithContext():
@@ -147,6 +169,40 @@ def test_find_one_or_404(self):
self.assertRaises(NotFound, self.db.BlogPost.find_one_or_404,
{'title': u'Flask is great'})
+class BaseTestCaseWithAuth():
+ def setUp(self):
+ db = 'flask_testing_auth'
+ conn = Connection()
+ conn[db].add_user('test', 'test')
+
+ self.app = create_app()
+ self.app.config['TESTING'] = True
+ self.app.config['MONGODB_DATABASE'] = db
+
+ self.db = MongoKit(self.app)
+
+ def test_correct_login(self):
+ self.app.config['MONGODB_USERNAME'] = 'test'
+ self.app.config['MONGODB_PASSWORD'] = 'test'
+
+ self.db.connect()
+
+ def test_incorrect_login(self):
+ self.app.config['MONGODB_USERNAME'] = 'fuu'
+ self.app.config['MONGODB_PASSWORD'] = 'baa'
+
+ self.assertRaises(AuthenticationIncorrect, self.db.connect)
+
+class TestCaseInitAppWithRequestContext(BaseTestCaseInitAppWithContext, unittest.TestCase):
+ def setUp(self):
+ self.app = create_app()
+
+ self.ctx = self.app.test_request_context('/')
+ self.ctx.push()
+
+ def tearDown(self):
+ self.ctx.pop()
+
class TestCaseWithRequestContext(BaseTestCaseWithContext, unittest.TestCase):
def setUp(self):
self.app = create_app()
@@ -158,8 +214,28 @@ def setUp(self):
def tearDown(self):
self.ctx.pop()
+class TestCaseWithRequestContextAuth(BaseTestCaseWithAuth, unittest.TestCase):
+ def setUp(self):
+ super(TestCaseWithRequestContextAuth, self).setUp()
+
+ self.ctx = self.app.test_request_context('/')
+ self.ctx.push()
+
+ def tearDown(self):
+ self.ctx.pop()
+
# Only testing is the flask version support app context (since flask v0.9)
if hasattr(Flask, "app_context"):
+ class TestCaseInitAppWithAppContext(BaseTestCaseInitAppWithContext, unittest.TestCase):
+ def setUp(self):
+ self.app = create_app()
+
+ self.ctx = self.app.app_context()
+ self.ctx.push()
+
+ def tearDown(self):
+ self.ctx.pop()
+
class TestCaseWithAppContext(BaseTestCaseWithContext, unittest.TestCase):
def setUp(self):
self.app = create_app()
@@ -170,14 +246,29 @@ def setUp(self):
def tearDown(self):
self.ctx.pop()
+
+ class TestCaseWithAppContextAuth(BaseTestCaseWithAuth, unittest.TestCase):
+ def setUp(self):
+ super(TestCaseWithAppContextAuth, self).setUp()
+
+ self.ctx = self.app.app_context()
+ self.ctx.push()
+
+ def tearDown(self):
+ self.ctx.pop()
+
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestCaseContextIndependent))
+ suite.addTest(unittest.makeSuite(TestCaseInitAppWithRequestContext))
suite.addTest(unittest.makeSuite(TestCaseWithRequestContext))
+ suite.addTest(unittest.makeSuite(TestCaseWithRequestContextAuth))
if hasattr(Flask, "app_context"):
+ suite.addTest(unittest.makeSuite(TestCaseInitAppWithAppContext))
suite.addTest(unittest.makeSuite(TestCaseWithAppContext))
+ suite.addTest(unittest.makeSuite(TestCaseWithAppContextAuth))
return suite
if __name__ == '__main__':
Please sign in to comment.
Something went wrong with that request. Please try again.