Add error handling

This commit is contained in:
vrde 2016-12-05 14:09:40 +01:00 committed by Sylvain Bellemare
parent c9a3d01112
commit 2fd0aeca9f
2 changed files with 39 additions and 8 deletions

View File

@ -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

View File

@ -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')