I originally changed the exception name from `ConnectionError` to `MongoEngineConnectionError` inb02904ee75
, inspired by landscape.io's package health report, which argued that `ConnectionError` is already a built-in exception in Python 3 (which it is: https://docs.python.org/3/library/exceptions.html#ConnectionError). I do agree that we shouldn't override built-in exceptions. [0] That said, it’s silly to add a "MongoEngine" prefix to any class within the `mongoengine` module (and *especially* to *just one* exception class out of many). I've decided to do what PyMongo does (8855a510a8/pymongo/errors.py (L59)
) and call this exception `ConnectionFailure`. Note that this is a breaking change and people will need to rename `MongoEngineConnectionError`s in their code to `ConnectionFailure`. Moreover, if they use PyMongo's `ConnectionFailure` for anything, they'll need to take extra care to avoid conflicts, e.g. by using: ``` from mongoengine import ConnectionFailure as MongoEngineConnectionFailure ``` [0] Note that some popular packages still overwrite `ConnectionError`, e.g.4983a9bde3/requests/exceptions.py (L32)
or0be4d29206/redis/exceptions.py (L8)
47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
import unittest
|
|
|
|
from pymongo import ReadPreference
|
|
from pymongo import MongoClient
|
|
|
|
import mongoengine
|
|
from mongoengine.connection import ConnectionFailure
|
|
|
|
|
|
CONN_CLASS = MongoClient
|
|
READ_PREF = ReadPreference.SECONDARY
|
|
|
|
|
|
class ConnectionTest(unittest.TestCase):
|
|
def setUp(self):
|
|
mongoengine.connection._connection_settings = {}
|
|
mongoengine.connection._connections = {}
|
|
mongoengine.connection._dbs = {}
|
|
|
|
def tearDown(self):
|
|
mongoengine.connection._connection_settings = {}
|
|
mongoengine.connection._connections = {}
|
|
mongoengine.connection._dbs = {}
|
|
|
|
def test_replicaset_uri_passes_read_preference(self):
|
|
"""Requires a replica set called "rs" on port 27017
|
|
"""
|
|
|
|
try:
|
|
conn = mongoengine.connect(
|
|
db="mongoenginetest",
|
|
host="mongodb://localhost/mongoenginetest?replicaSet=rs",
|
|
read_preference=READ_PREF,
|
|
)
|
|
except ConnectionFailure as e:
|
|
return
|
|
|
|
if not isinstance(conn, CONN_CLASS):
|
|
# really???
|
|
return
|
|
|
|
self.assertEqual(conn.read_preference, READ_PREF)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|