Skip to content

Commit 7d47a71

Browse files
authored
Merge pull request #304 from touilleMan/fix-test-and-mongomock
Fix test and mongomock
2 parents 7d71fef + 0d6b4f5 commit 7d47a71

File tree

4 files changed

+82
-12
lines changed

4 files changed

+82
-12
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ that much better:
3535
* Denny Huang - https://github.com/denny0223
3636
* Stefan Wojcik - https://github.com/wojcikstefan
3737
* John Cass - https://github.com/jcass77
38+
* Aly Sivji - https://github.com/alysivji

flask_mongoengine/connection.py

+17-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
import mongoengine
22
from pymongo import ReadPreference, uri_parser
33

4+
45
__all__ = (
56
'create_connections', 'get_connection_settings', 'InvalidSettingsError',
67
)
78

89

10+
MONGODB_CONF_VARS = ('MONGODB_ALIAS', 'MONGODB_DB', 'MONGODB_HOST', 'MONGODB_IS_MOCK',
11+
'MONGODB_PASSWORD', 'MONGODB_PORT', 'MONGODB_USERNAME')
12+
13+
914
class InvalidSettingsError(Exception):
1015
pass
1116

@@ -24,7 +29,15 @@ def _sanitize_settings(settings):
2429

2530
# Handle uri style connections
2631
if "://" in resolved_settings.get('host', ''):
27-
uri_dict = uri_parser.parse_uri(resolved_settings['host'])
32+
# this section pulls the database name from the URI
33+
# PyMongo requires URI to start with mongodb:// to parse
34+
# this workaround allows mongomock to work
35+
uri_to_check = resolved_settings['host']
36+
37+
if uri_to_check.startswith('mongomock://'):
38+
uri_to_check = uri_to_check.replace('mongomock://', 'mongodb://')
39+
40+
uri_dict = uri_parser.parse_uri(uri_to_check)
2841
resolved_settings['db'] = uri_dict['database']
2942

3043
# Add a default name param or use the "db" key if exists
@@ -74,10 +87,10 @@ def get_connection_settings(config):
7487
else:
7588
return _sanitize_settings(settings)
7689

77-
# If "MONGODB_SETTINGS" doesn't exist, sanitize all the keys starting with
78-
# "MONGODB_" as if they all describe a single connection.
90+
# If "MONGODB_SETTINGS" doesn't exist, sanitize the "MONGODB_" keys
91+
# as if they all describe a single connection.
7992
else:
80-
config = dict((k, v) for k, v in config.items() if k.startswith('MONGODB_')) # ugly dict comprehention in order to support python 2.6
93+
config = dict((k, v) for k, v in config.items() if k in MONGODB_CONF_VARS) # ugly dict comprehention in order to support python 2.6
8194
return _sanitize_settings(config)
8295

8396

tests/__init__.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import unittest
2-
32
import flask
3+
import mongoengine
44

55

66
class FlaskMongoEngineTestCase(unittest.TestCase):
@@ -12,6 +12,13 @@ def setUp(self):
1212
self.app.config['TESTING'] = True
1313
self.ctx = self.app.app_context()
1414
self.ctx.push()
15+
# Mongoengine keep a global state of the connections that must be
16+
# reset before each test.
17+
# Given it doesn't expose any method to get the list of registered
18+
# connections, we have to do the cleaning by hand...
19+
mongoengine.connection._connection_settings.clear()
20+
mongoengine.connection._connections.clear()
21+
mongoengine.connection._dbs.clear()
1522

1623
def tearDown(self):
1724
self.ctx.pop()

tests/test_connection.py

+56-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
import mongoengine
12
from mongoengine.context_managers import switch_db
3+
from nose import SkipTest
4+
from nose.tools import assert_raises
25
import pymongo
36
from pymongo.errors import InvalidURI
47
from pymongo.read_preferences import ReadPreference
@@ -10,14 +13,21 @@
1013

1114
class ConnectionTestCase(FlaskMongoEngineTestCase):
1215

13-
def _do_persist(self, db):
16+
def _do_persist(self, db, alias=None):
1417
"""Initialize a test Flask application and persist some data in
1518
MongoDB, ultimately asserting that the connection works.
1619
"""
17-
class Todo(db.Document):
18-
title = db.StringField(max_length=60)
19-
text = db.StringField()
20-
done = db.BooleanField(default=False)
20+
if alias:
21+
class Todo(db.Document):
22+
meta = {'db_alias': alias}
23+
title = db.StringField(max_length=60)
24+
text = db.StringField()
25+
done = db.BooleanField(default=False)
26+
else:
27+
class Todo(db.Document):
28+
title = db.StringField(max_length=60)
29+
text = db.StringField()
30+
done = db.BooleanField(default=False)
2131

2232
db.init_app(self.app)
2333
Todo.drop_collection()
@@ -41,7 +51,7 @@ def test_simple_connection(self):
4151
'PORT': 27017,
4252
'DB': 'flask_mongoengine_test_db'
4353
}
44-
self._do_persist(db)
54+
self._do_persist(db, alias='simple_conn')
4555

4656
def test_host_as_uri_string(self):
4757
"""Make sure we can connect to a standalone MongoDB if we specify
@@ -51,14 +61,43 @@ def test_host_as_uri_string(self):
5161
self.app.config['MONGODB_HOST'] = 'mongodb://localhost:27017/flask_mongoengine_test_db'
5262
self._do_persist(db)
5363

64+
def test_mongomock_host_as_uri_string(self):
65+
"""Make sure we switch to mongomock if we specify the host as a mongomock URI.
66+
"""
67+
if mongoengine.VERSION < (0, 9, 0):
68+
raise SkipTest('Mongomock not supported for mongoengine < 0.9.0')
69+
db = MongoEngine()
70+
self.app.config['MONGODB_HOST'] = 'mongomock://localhost:27017/flask_mongoengine_test_db'
71+
with assert_raises(RuntimeError) as exc:
72+
self._do_persist(db)
73+
assert str(exc.exception) == 'You need mongomock installed to mock MongoEngine.'
74+
75+
def test_mongomock_as_param(self):
76+
"""Make sure we switch to mongomock when providing IS_MOCK option.
77+
"""
78+
if mongoengine.VERSION < (0, 9, 0):
79+
raise SkipTest('Mongomock not supported for mongoengine < 0.9.0')
80+
db = MongoEngine()
81+
self.app.config['MONGODB_SETTINGS'] = {
82+
'ALIAS': 'simple_conn',
83+
'HOST': 'localhost',
84+
'PORT': 27017,
85+
'DB': 'flask_mongoengine_test_db',
86+
'IS_MOCK': True
87+
}
88+
with assert_raises(RuntimeError) as exc:
89+
self._do_persist(db, alias='simple_conn')
90+
assert str(exc.exception) == 'You need mongomock installed to mock MongoEngine.'
91+
5492
def test_host_as_list(self):
5593
"""Make sure MONGODB_HOST can be a list hosts."""
5694
db = MongoEngine()
5795
self.app.config['MONGODB_SETTINGS'] = {
5896
'ALIAS': 'host_list',
5997
'HOST': ['localhost:27017'],
98+
'DB': 'flask_mongoengine_test_db'
6099
}
61-
self._do_persist(db)
100+
self._do_persist(db, alias='host_list')
62101

63102
def test_multiple_connections(self):
64103
"""Make sure establishing multiple connections to a standalone
@@ -117,6 +156,16 @@ def test_connection_with_invalid_uri(self):
117156
self.app.config['MONGODB_HOST'] = 'mongo://localhost'
118157
self.assertRaises(InvalidURI, MongoEngine, self.app)
119158

159+
def test_ingnored_mongodb_prefix_config(self):
160+
"""Config starting by MONGODB_ but not used by flask-mongoengine
161+
should be ignored.
162+
"""
163+
db = MongoEngine()
164+
self.app.config['MONGODB_HOST'] = 'mongodb://localhost:27017/flask_mongoengine_test_db_prod'
165+
# Invalid host, should trigger exception if used
166+
self.app.config['MONGODB_TEST_HOST'] = 'dummy://localhost:27017/test'
167+
self._do_persist(db)
168+
120169
def test_connection_kwargs(self):
121170
"""Make sure additional connection kwargs work."""
122171

0 commit comments

Comments
 (0)