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
|
import mongoengine
import pymongo
import pytest
from mongoengine.connection import ConnectionFailure
from mongoengine.context_managers import switch_db
from pymongo.database import Database
from pymongo.errors import InvalidURI
from pymongo.mongo_client import MongoClient
from pymongo.read_preferences import ReadPreference
from flask_mongoengine import MongoEngine, current_mongoengine_instance
def test_connection__should_use_defaults__if_no_settings_provided(app):
"""Make sure a simple connection to a standalone MongoDB works."""
db = MongoEngine()
# Verify no extension for Mongoengine yet created for app
assert app.extensions == {}
assert current_mongoengine_instance() is None
# Create db connection. Should return None.
assert db.init_app(app) is None
# Verify db added to Flask extensions.
assert current_mongoengine_instance() == db
# Verify db settings passed to pymongo driver.
# Default mongoengine db is 'default', default Flask-Mongoengine db is 'test'.
connection = mongoengine.get_connection()
mongo_engine_db = mongoengine.get_db()
assert isinstance(mongo_engine_db, Database)
assert isinstance(connection, MongoClient)
assert mongo_engine_db.name == "test"
assert connection.HOST == "localhost"
assert connection.PORT == 27017
@pytest.mark.parametrize(
("config_extension"),
[
{
"MONGODB_SETTINGS": {
"ALIAS": "simple_conn",
"HOST": "localhost",
"PORT": 27017,
"DB": "flask_mongoengine_test_db",
}
},
{
"MONGODB_HOST": "localhost",
"MONGODB_PORT": 27017,
"MONGODB_DB": "flask_mongoengine_test_db",
"MONGODB_ALIAS": "simple_conn",
},
],
ids=("Dict format", "Config variable format"),
)
def test_connection__should_pass_alias__if_provided(app, config_extension):
"""Make sure a simple connection pass ALIAS setting variable."""
db = MongoEngine()
app.config.update(config_extension)
# Verify no extension for Mongoengine yet created for app
assert app.extensions == {}
assert current_mongoengine_instance() is None
# Create db connection. Should return None.
assert db.init_app(app) is None
# Verify db added to Flask extensions.
assert current_mongoengine_instance() == db
# Verify db settings passed to pymongo driver.
# ALIAS is used to find correct connection.
# As we do not use default alias, default call to mongoengine.get_connection
# should raise.
with pytest.raises(ConnectionFailure):
mongoengine.get_connection()
connection = mongoengine.get_connection("simple_conn")
mongo_engine_db = mongoengine.get_db("simple_conn")
assert isinstance(mongo_engine_db, Database)
assert isinstance(connection, MongoClient)
assert mongo_engine_db.name == "flask_mongoengine_test_db"
assert connection.HOST == "localhost"
assert connection.PORT == 27017
@pytest.mark.parametrize(
("config_extension"),
[
{
"MONGODB_SETTINGS": {
"HOST": "mongodb://localhost:27017/flask_mongoengine_test_db"
}
},
{
"MONGODB_HOST": "mongodb://localhost:27017/flask_mongoengine_test_db",
"MONGODB_PORT": 27017,
"MONGODB_DB": "should_ignore_it",
},
],
ids=("Dict format", "Config variable format"),
)
def test_connection__should_parse_host_uri__if_host_formatted_as_uri(
app, config_extension
):
"""Make sure a simple connection pass ALIAS setting variable."""
db = MongoEngine()
app.config.update(config_extension)
# Verify no extension for Mongoengine yet created for app
assert app.extensions == {}
assert current_mongoengine_instance() is None
# Create db connection. Should return None.
assert db.init_app(app) is None
# Verify db added to Flask extensions.
assert current_mongoengine_instance() == db
connection = mongoengine.get_connection()
mongo_engine_db = mongoengine.get_db()
assert isinstance(mongo_engine_db, Database)
assert isinstance(connection, MongoClient)
assert mongo_engine_db.name == "flask_mongoengine_test_db"
assert connection.HOST == "localhost"
assert connection.PORT == 27017
@pytest.mark.parametrize(
("config_extension"),
[
{
"MONGODB_SETTINGS": {
"HOST": "mongomock://localhost:27017/flask_mongoengine_test_db"
}
},
{
"MONGODB_SETTINGS": {
"ALIAS": "simple_conn",
"HOST": "localhost",
"PORT": 27017,
"DB": "flask_mongoengine_test_db",
"IS_MOCK": True,
}
},
{"MONGODB_HOST": "mongomock://localhost:27017/flask_mongoengine_test_db"},
],
ids=("Dict format as URI", "Dict format as Param", "Config variable format as URI"),
)
def test_connection__should_parse_mongo_mock_uri__as_uri_and_as_settings(
app, config_extension
):
"""Make sure a simple connection pass ALIAS setting variable."""
db = MongoEngine()
app.config.update(config_extension)
# Verify no extension for Mongoengine yet created for app
assert app.extensions == {}
assert current_mongoengine_instance() is None
# Create db connection. Should return None.
with pytest.raises(RuntimeError) as error:
assert db.init_app(app) is None
assert str(error.value) == "You need mongomock installed to mock MongoEngine."
@pytest.mark.parametrize(
("config_extension"),
[
{
"MONGODB_SETTINGS": {
"HOST": "postgre://localhost:27017/flask_mongoengine_test_db"
}
},
{"MONGODB_HOST": "mysql://localhost:27017/flask_mongoengine_test_db"},
],
ids=("Dict format as URI", "Config variable format as URI"),
)
def test_connection__should_raise__if_uri_not_properly_formatted(app, config_extension):
"""Make sure a simple connection pass ALIAS setting variable."""
db = MongoEngine()
app.config.update(config_extension)
# Verify no extension for Mongoengine yet created for app
assert app.extensions == {}
assert current_mongoengine_instance() is None
# Create db connection. Should return None.
with pytest.raises(InvalidURI) as error:
assert db.init_app(app) is None
assert (
str(error.value)
== "Invalid URI scheme: URI must begin with 'mongodb://' or 'mongodb+srv://'"
)
def test_connection__should_accept_host_as_list(app):
"""Make sure MONGODB_HOST can be a list hosts."""
db = MongoEngine()
app.config["MONGODB_SETTINGS"] = {
"ALIAS": "host_list",
"HOST": ["localhost:27017"],
"DB": "flask_mongoengine_list_test_db",
}
db.init_app(app)
connection = mongoengine.get_connection("host_list")
mongo_engine_db = mongoengine.get_db("host_list")
assert isinstance(mongo_engine_db, Database)
assert isinstance(connection, MongoClient)
assert mongo_engine_db.name == "flask_mongoengine_list_test_db"
assert connection.HOST == "localhost"
assert connection.PORT == 27017
def test_multiple_connections(app):
"""Make sure establishing multiple connections to a standalone
MongoDB and switching between them works.
"""
db = MongoEngine()
app.config["MONGODB_SETTINGS"] = [
{
"ALIAS": "default",
"DB": "flask_mongoengine_test_db_1",
"HOST": "localhost",
"PORT": 27017,
},
{
"ALIAS": "alternative",
"DB": "flask_mongoengine_test_db_2",
"HOST": "localhost",
"PORT": 27017,
},
]
class Todo(db.Document):
title = db.StringField(max_length=60)
db.init_app(app)
# Drop default collection from init
Todo.drop_collection()
Todo.meta = {"db_alias": "alternative"}
# Drop 'alternative' collection initiated early.
Todo.drop_collection()
# Make sure init correct and both databases are clean
with switch_db(Todo, "default") as Todo:
doc = Todo.objects().first()
assert doc is None
with switch_db(Todo, "alternative") as Todo:
doc = Todo.objects().first()
assert doc is None
# Test saving a doc via the default connection
with switch_db(Todo, "default") as Todo:
todo = Todo()
todo.text = "Sample"
todo.title = "Testing"
todo.done = True
s_todo = todo.save()
f_to = Todo.objects().first()
assert s_todo.title == f_to.title
# Make sure the doc still doesn't exist in the alternative db
with switch_db(Todo, "alternative") as Todo:
doc = Todo.objects().first()
assert doc is None
# Make sure switching back to the default connection shows the doc
with switch_db(Todo, "default") as Todo:
doc = Todo.objects().first()
assert doc is not None
def test_ingnored_mongodb_prefix_config(app):
"""Config starting by MONGODB_ but not used by flask-mongoengine
should be ignored.
"""
db = MongoEngine()
app.config[
"MONGODB_HOST"
] = "mongodb://localhost:27017/flask_mongoengine_test_db_prod"
# Invalid host, should trigger exception if used
app.config["MONGODB_TEST_HOST"] = "dummy://localhost:27017/test"
db.init_app(app)
connection = mongoengine.get_connection()
mongo_engine_db = mongoengine.get_db()
assert isinstance(mongo_engine_db, Database)
assert isinstance(connection, MongoClient)
assert mongo_engine_db.name == "flask_mongoengine_test_db_prod"
assert connection.HOST == "localhost"
assert connection.PORT == 27017
def test_connection_kwargs(app):
"""Make sure additional connection kwargs work."""
# Figure out whether to use "MAX_POOL_SIZE" or "MAXPOOLSIZE" based
# on PyMongo version (former was changed to the latter as described
# in https://jira.mongodb.org/browse/PYTHON-854)
# TODO remove once PyMongo < 3.0 support is dropped
if pymongo.version_tuple[0] >= 3:
MAX_POOL_SIZE_KEY = "MAXPOOLSIZE"
else:
MAX_POOL_SIZE_KEY = "MAX_POOL_SIZE"
app.config["MONGODB_SETTINGS"] = {
"ALIAS": "tz_aware_true",
"DB": "flask_mongoengine_testing_tz_aware",
"TZ_AWARE": True,
"READ_PREFERENCE": ReadPreference.SECONDARY,
MAX_POOL_SIZE_KEY: 10,
}
db = MongoEngine(app)
assert db.connection.codec_options.tz_aware
assert db.connection.max_pool_size == 10
assert db.connection.read_preference == ReadPreference.SECONDARY
|