diff --git a/bigchaindb/backend/connection.py b/bigchaindb/backend/connection.py index 975d9df7..2fc7d856 100644 --- a/bigchaindb/backend/connection.py +++ b/bigchaindb/backend/connection.py @@ -1,11 +1,24 @@ -class ConnectionError(Exception): - """Raised when there is a connection error when running a query.""" +from bigchaindb.common.exceptions import ConfigurationError +from importlib import import_module + + +BACKENDS = { + 'rethinkdb': 'bigchaindb.backend.rethinkdb.connection.RethinkDBConnection' +} + + +def connect(backend, host, port, dbname): + try: + module_name, _, class_name = BACKENDS[backend].rpartition('.') + Class = getattr(import_module(module_name), class_name) + except KeyError: + raise ConfigurationError('Backend `{}` is not supported. ' + 'BigchainDB currently supports {}'.format(backend, BACKENDS.keys())) + except (ImportError, AttributeError) as exc: + raise ConfigurationError('Error loading backend `{}`'.format(backend)) from exc + + return Class(host, port, dbname) class Connection: - - def run(self): - raise NotImplementedError() - - def connect(self): - raise NotImplementedError() + pass diff --git a/tests/backend/test_connection.py b/tests/backend/test_connection.py index 6fb6478d..4300141f 100644 --- a/tests/backend/test_connection.py +++ b/tests/backend/test_connection.py @@ -1,3 +1,6 @@ +import pytest + + def test_get_connection_returns_the_correct_instance(): from bigchaindb.backend import connect from bigchaindb.backend.connection import Connection @@ -13,3 +16,18 @@ def test_get_connection_returns_the_correct_instance(): conn = connect(**config) assert isinstance(conn, Connection) assert isinstance(conn, RethinkDBConnection) + + +def test_get_connection_raises_a_configuration_error(monkeypatch): + from bigchaindb.common.exceptions import ConfigurationError + from bigchaindb.backend import connect + + with pytest.raises(ConfigurationError): + connect('msaccess', 'localhost', '1337', 'mydb') + + with pytest.raises(ConfigurationError): + # We need to force a misconfiguration here + monkeypatch.setattr('bigchaindb.backend.connection.BACKENDS', + {'catsandra': 'bigchaindb.backend.meowmeow.Catsandra'}) + + connect('catsandra', 'localhost', '1337', 'mydb')