Example #1
0
    def test_connect_connectionerror(self):
        """Test that `connect()` raises `ConnectionError()`."""

        with mock.patch('simon.connection._get_connection') as mock_method:
            mock_method.return_value = ({'test': mock.Mock()}, {})

            with self.assertRaises(connection.ConnectionError):
                connection.connect()
Example #2
0
    def test_connect_connectionerror(self):
        """Test that `connect()` raises `ConnectionError()`."""

        with mock.patch('simon.connection._get_connection') as mock_method:
            mock_method.return_value = ({'test': mock.Mock()}, {})

            with self.assertRaises(connection.ConnectionError):
                connection.connect()
Example #3
0
 def setUpClass(cls):
     with mock.patch('simon.connection.MongoClient'):
         cls.connection = connection.connect('localhost', name='test-simon')
Example #4
0
    def init_app(self, app, prefix='MONGO', alias=None):
        """Initializes the Flask app for use with Simon.

        This method will automatically be called if the app is passed
        into ``__init__()``.

        :param app: the Flask application.
        :type app: :class:`flask.Flask`
        :param prefix: (optional) the prefix of the config settings
        :type prefix: str
        :param alias: (optional) the alias to use for the database
                      connection
        :type alias: str

        .. versionchanged:: 0.2.0
           Added support for multiple databases
        .. versionadded:: 0.1.0
        """

        if 'simon' not in app.extensions:
            app.extensions['simon'] = {}

        app.url_map.converters['objectid'] = ObjectIDConverter

        def prefixed(name):
            """Prepends the prefix to the key name."""

            return '{0}_{1}'.format(prefix, name)

        # The URI key is accessed a few times, so be lazy and only
        # generate the prefixed version once.
        uri_key = prefixed('URI')

        if uri_key in app.config:
            parsed = uri_parser.parse_uri(app.config[uri_key])
            if not parsed.get('database'):
                message = '{0} does not contain a database name.'
                message = message.format(uri_key)
                raise ValueError(message)

            host = app.config[uri_key]

            name = app.config[prefixed('DBNAME')] = parsed['database']
            username = app.config[prefixed('USERNAME')] = parsed['username']
            password = app.config[prefixed('PASSWORD')] = parsed['password']

            replica_set = parsed['options'].get('replicaset', None)
            app.config[prefixed('REPLICA_SET')] = replica_set
        else:
            host_key = prefixed('HOST')
            port_key = prefixed('PORT')
            name_key = prefixed('DBNAME')
            username_key = prefixed('USERNAME')
            password_key = prefixed('PASSWORD')
            replica_set_key = prefixed('REPLICA_SET')

            app.config.setdefault(host_key, 'localhost')
            app.config.setdefault(port_key, 27017)
            app.config.setdefault(name_key, app.name)

            app.config.setdefault(username_key, None)
            app.config.setdefault(password_key, None)
            app.config.setdefault(replica_set_key, None)

            host = app.config[host_key]
            port = app.config[port_key]
            name = app.config[name_key]
            username = app.config[username_key]
            password = app.config[password_key]
            replica_set = app.config[replica_set_key]

            host = '{0}:{1}'.format(host, port)

        connection.connect(host,
                           name=name,
                           alias=alias,
                           username=username,
                           password=password,
                           replica_set=replica_set)
Example #5
0
 def setUpClass(cls):
     cls.connection = connection.connect(name='simon-integration')
     cls.db = cls.connection['simon-integration']
     cls.collection = cls.db['simon-integration']
Example #6
0
 def setUpClass(cls):
     with mock.patch("simon.connection.MongoClient"):
         cls.connection = connection.connect("localhost", name="test-simon")
Example #7
0
    def test_connect(self):
        """Test the `connect()` method."""

        with mock.patch('simon.connection._get_connection') as mock_method:
            mock_method.return_value = ({'test': mock.Mock()}, {})
            connection.connect(name='test')
            mock_method.assert_called_with(host='localhost',
                                           port=None,
                                           replica_set=None)

            mock_method.return_value = ({'test': mock.Mock()}, {})
            connection.connect(name='test', alias='test2')
            mock_method.assert_called_with(host='localhost',
                                           port=None,
                                           replica_set=None)

            mock_method.return_value = ({'test3': mock.Mock()}, {})
            connection.connect(host='someotherhost', name='test3', port=1234)
            mock_method.assert_called_with(host='someotherhost',
                                           port=1234,
                                           replica_set=None)

            mock_method.return_value = ({'simon': mock.Mock()}, {})
            connection.connect(host='simon.mongo.com',
                               name='simon',
                               port=27017,
                               username='******',
                               password='******')
            mock_method.assert_called_with(host='simon.mongo.com',
                                           port=27017,
                                           replica_set=None)

            mock_method.return_value = ({
                'simon': mock.Mock()
            }, {
                'name': 'simon',
                'username': '******',
                'password': '******',
            })
            url = 'mongodb://*****:*****@simon.mongo.com:27017/simon'
            connection.connect(host=url, alias='remote_uri')
            mock_method.assert_called_with(host=url,
                                           port=None,
                                           replica_set=None)

            mock_method.return_value = ({
                'simon-rs': mock.Mock()
            }, {
                'name': 'simon-rs',
                'username': '******',
                'password': '******',
            })
            url = 'mongodb://*****:*****@simon.m0.mongo.com:27017/simon-rs'
            connection.connect(host=url,
                               replica_set='simonrs',
                               alias='replica1')
            mock_method.assert_called_with(host=url,
                                           port=None,
                                           replica_set='simonrs')

            mock_method.return_value = ({
                'simon-rs': mock.Mock()
            }, {
                'name': 'simon-rs',
                'username': '******',
                'password': '******',
            })
            url = ('mongodb://*****:*****@simon.m0.mongo.com:27017,'
                   'simon.m1.mongo.com:27017/simon-rs')
            connection.connect(host=url,
                               replica_set='simonrs',
                               alias='replica2')
            mock_method.assert_called_with(host=url,
                                           port=None,
                                           replica_set='simonrs')

        self.assertIn('test', connection._databases)
        self.assertIn('test2', connection._databases)
        self.assertIn('test3', connection._databases)
        self.assertIn('simon', connection._databases)
        self.assertIn('remote_uri', connection._databases)
        self.assertIn('replica1', connection._databases)
        self.assertIn('replica2', connection._databases)

        self.assertIn('default', connection._databases)

        self.assertEqual(connection._databases['test'],
                         connection._databases['default'])
        self.assertNotEqual(connection._databases['test'],
                            connection._databases['test2'])
Example #8
0
    def init_app(self, app, prefix="MONGO", alias=None):
        """Initializes the Flask app for use with Simon.

        This method will automatically be called if the app is passed
        into ``__init__()``.

        :param app: the Flask application.
        :type app: :class:`flask.Flask`
        :param prefix: (optional) the prefix of the config settings
        :type prefix: str
        :param alias: (optional) the alias to use for the database
                      connection
        :type alias: str

        .. versionchanged:: 0.2.0
           Added support for multiple databases
        .. versionadded:: 0.1.0
        """

        if "simon" not in app.extensions:
            app.extensions["simon"] = {}

        app.url_map.converters["objectid"] = ObjectIDConverter

        def prefixed(name):
            """Prepends the prefix to the key name."""

            return "{0}_{1}".format(prefix, name)

        # The URI key is accessed a few times, so be lazy and only
        # generate the prefixed version once.
        uri_key = prefixed("URI")

        if uri_key in app.config:
            parsed = uri_parser.parse_uri(app.config[uri_key])
            if not parsed.get("database"):
                message = "{0} does not contain a database name."
                message = message.format(uri_key)
                raise ValueError(message)

            host = app.config[uri_key]

            name = app.config[prefixed("DBNAME")] = parsed["database"]
            username = app.config[prefixed("USERNAME")] = parsed["username"]
            password = app.config[prefixed("PASSWORD")] = parsed["password"]

            replica_set = parsed["options"].get("replicaset", None)
            app.config[prefixed("REPLICA_SET")] = replica_set
        else:
            host_key = prefixed("HOST")
            port_key = prefixed("PORT")
            name_key = prefixed("DBNAME")
            username_key = prefixed("USERNAME")
            password_key = prefixed("PASSWORD")
            replica_set_key = prefixed("REPLICA_SET")

            app.config.setdefault(host_key, "localhost")
            app.config.setdefault(port_key, 27017)
            app.config.setdefault(name_key, app.name)

            app.config.setdefault(username_key, None)
            app.config.setdefault(password_key, None)
            app.config.setdefault(replica_set_key, None)

            host = app.config[host_key]
            port = app.config[port_key]
            name = app.config[name_key]
            username = app.config[username_key]
            password = app.config[password_key]
            replica_set = app.config[replica_set_key]

            host = "{0}:{1}".format(host, port)

        connection.connect(host, name=name, alias=alias, username=username, password=password, replica_set=replica_set)
Example #9
0
 def setUpClass(cls):
     cls.connection = connection.connect(name='simon-integration')
     cls.db = cls.connection['simon-integration']
     cls.collection = cls.db['simon-integration']
Example #10
0
 def setUpClass(cls):
     with mock.patch('simon.connection.MongoClient'):
         cls.connection = connection.connect('localhost', name='test-simon')
Example #11
0
    def test_connect(self):
        """Test the `connect()` method."""

        with mock.patch('simon.connection._get_connection') as mock_method:
            mock_method.return_value = ({'test': mock.Mock()}, {})
            connection.connect(name='test')
            mock_method.assert_called_with(host='localhost', port=None,
                                           replica_set=None)

            mock_method.return_value = ({'test': mock.Mock()}, {})
            connection.connect(name='test', alias='test2')
            mock_method.assert_called_with(host='localhost', port=None,
                                           replica_set=None)

            mock_method.return_value = ({'test3': mock.Mock()}, {})
            connection.connect(host='someotherhost', name='test3', port=1234)
            mock_method.assert_called_with(host='someotherhost', port=1234,
                                           replica_set=None)

            mock_method.return_value = ({'simon': mock.Mock()}, {})
            connection.connect(host='simon.mongo.com', name='simon',
                               port=27017, username='******',
                               password='******')
            mock_method.assert_called_with(host='simon.mongo.com', port=27017,
                                           replica_set=None)

            mock_method.return_value = ({'simon': mock.Mock()}, {
                'name': 'simon',
                'username': '******',
                'password': '******',
            })
            url = 'mongodb://*****:*****@simon.mongo.com:27017/simon'
            connection.connect(host=url, alias='remote_uri')
            mock_method.assert_called_with(host=url, port=None,
                                           replica_set=None)

            mock_method.return_value = ({'simon-rs': mock.Mock()}, {
                'name': 'simon-rs',
                'username': '******',
                'password': '******',
            })
            url = 'mongodb://*****:*****@simon.m0.mongo.com:27017/simon-rs'
            connection.connect(host=url, replica_set='simonrs',
                               alias='replica1')
            mock_method.assert_called_with(host=url, port=None,
                                           replica_set='simonrs')

            mock_method.return_value = ({'simon-rs': mock.Mock()}, {
                'name': 'simon-rs',
                'username': '******',
                'password': '******',
            })
            url = ('mongodb://*****:*****@simon.m0.mongo.com:27017,'
                   'simon.m1.mongo.com:27017/simon-rs')
            connection.connect(host=url, replica_set='simonrs',
                               alias='replica2')
            mock_method.assert_called_with(host=url, port=None,
                                           replica_set='simonrs')

        self.assertIn('test', connection._databases)
        self.assertIn('test2', connection._databases)
        self.assertIn('test3', connection._databases)
        self.assertIn('simon', connection._databases)
        self.assertIn('remote_uri', connection._databases)
        self.assertIn('replica1', connection._databases)
        self.assertIn('replica2', connection._databases)

        self.assertIn('default', connection._databases)

        self.assertEqual(connection._databases['test'],
                         connection._databases['default'])
        self.assertNotEqual(connection._databases['test'],
                            connection._databases['test2'])