diff --git a/beanquery/__init__.py b/beanquery/__init__.py index e997631..d678954 100644 --- a/beanquery/__init__.py +++ b/beanquery/__init__.py @@ -46,7 +46,23 @@ def __init__(self, dsn='', **kwargs): def attach(self, dsn, **kwargs): scheme = urlparse(dsn).scheme - source = importlib.import_module(f'beanquery.sources.{scheme}') + if not scheme: + raise OperationalError('missing source scheme') + source_name = f'beanquery.sources.{scheme}' + try: + source = importlib.import_module(source_name) + except ModuleNotFoundError as exc: + # Dotted schemes can fail on a missing parent source package. + # Propagate import failures for other modules. + missing = exc.name + missing_source = ( + missing == source_name or + (missing is not None and missing.startswith('beanquery.sources.') and + source_name.startswith(f'{missing}.')) + ) + if not missing_source: + raise + raise OperationalError(f'unknown source scheme: {scheme!r}') from None source.attach(self, dsn, **kwargs) def close(self): diff --git a/beanquery/connection_test.py b/beanquery/connection_test.py new file mode 100644 index 0000000..ab2e766 --- /dev/null +++ b/beanquery/connection_test.py @@ -0,0 +1,72 @@ +import unittest +from unittest import mock + +import beanquery + + +class TestConnection(unittest.TestCase): + def test_connect_without_source(self): + for dsn in [None, '']: + with self.subTest(dsn=dsn): + connection = beanquery.connect(dsn) + self.assertEqual(connection.execute('SELECT 42').fetchall(), [(42,)]) + + def test_missing_scheme(self): + connection = beanquery.connect(None) + for dsn in ['', 'ledger.beancount', './ledger.beancount']: + with self.subTest(dsn=dsn), self.assertRaisesRegex(beanquery.OperationalError, '^missing source scheme$'): + connection.attach(dsn) + + def test_connect_missing_scheme(self): + with self.assertRaisesRegex(beanquery.OperationalError, '^missing source scheme$'): + beanquery.connect('ledger.beancount') + + def test_unknown_scheme(self): + for scheme in ['beancounnt', 'unknown', 'foo.bar', 'foo.bar.baz', 'foo+bar', 'foo-bar']: + with self.subTest(scheme=scheme): + with self.assertRaises(beanquery.OperationalError) as caught: + beanquery.connect(f'{scheme}:ledger') + self.assertEqual(str(caught.exception), f'unknown source scheme: {scheme!r}') + + def test_message_only_contains_scheme(self): + with self.assertRaises(beanquery.OperationalError) as caught: + beanquery.connect('unknown://example.invalid/private-ledger?fixture=synthetic') + self.assertEqual(str(caught.exception), "unknown source scheme: 'unknown'") + + def test_import_dependency_failure(self): + names = ['some_dependency', 'beanquery.sources', 'beanquery.sources.other', 'beanquery.sources.foo.optional', None] + for name in names: + error = ModuleNotFoundError('missing dependency', name=name) + with self.subTest(name=name), mock.patch('beanquery.importlib.import_module', side_effect=error): + with self.assertRaises(ModuleNotFoundError) as caught: + beanquery.connect('foo.bar:ledger') + self.assertIs(caught.exception, error) + + def test_import_error(self): + error = ImportError('source import failed') + with mock.patch('beanquery.importlib.import_module', side_effect=error): + with self.assertRaises(ImportError) as caught: + beanquery.connect('test:') + self.assertIs(caught.exception, error) + + def test_source_attach_failure(self): + error = ModuleNotFoundError('source attach failed', name='beanquery.sources.test') + source = mock.Mock() + source.attach.side_effect = error + with mock.patch('beanquery.importlib.import_module', return_value=source): + with self.assertRaises(ModuleNotFoundError) as caught: + beanquery.connect('test:') + self.assertIs(caught.exception, error) + + def test_source_attach_arguments(self): + source = mock.Mock() + dsn = 'test:fixture?name=example' + entries = [] + options = {'example': 'synthetic'} + with mock.patch('beanquery.importlib.import_module', return_value=source): + connection = beanquery.connect(dsn, entries=entries, options=options) + source.attach.assert_called_once_with(connection, dsn, entries=entries, options=options) + + def test_valid_source(self): + connection = beanquery.connect('test:magic?name=example&start=1&stop=3') + self.assertEqual(connection.execute('SELECT x FROM #example').fetchall(), [(1,), (2,)]) diff --git a/beanquery/query_render.py b/beanquery/query_render.py index 24d5361..107bedf 100644 --- a/beanquery/query_render.py +++ b/beanquery/query_render.py @@ -486,7 +486,7 @@ def _get_renderer(datatype, ctx): return renderer(ctx) -def render_text(columns, rows, dcontext, file, expand=False, boxed=False, +def render_text(columns, rows, dcontext, file, expand=False, boxed=False, # noqa: PLR0917 spaced=False, listsep=' ', nullvalue='', narrow=True, unicode=False, **kwargs): """Render the result of executing a query in text format. @@ -552,7 +552,7 @@ def render_text(columns, rows, dcontext, file, expand=False, boxed=False, file.write(bottom) -def render_csv(columns, rows, dcontext, file, expand=False, nullvalue='', **kwargs): +def render_csv(columns, rows, dcontext, file, expand=False, nullvalue='', **kwargs): # noqa: PLR0917 """Render the result of executing a query in text format. Args: diff --git a/beanquery/shell.py b/beanquery/shell.py index c28ab3b..3f96f74 100644 --- a/beanquery/shell.py +++ b/beanquery/shell.py @@ -53,7 +53,7 @@ def strip(cls, x): return cls.ESCAPES.sub('', x) -def render_location(text, pos, endpos, lineno, indent, strip, out): +def render_location(text, pos, endpos, lineno, indent, strip, out): # noqa: PLR0917 length = endpos - pos lines = text.splitlines(True) for line in lines[:lineno]: @@ -374,7 +374,7 @@ class BQLShell(DispatchingShell): """An interactive shell interpreter for the Beancount query language.""" prompt = 'beanquery> ' - def __init__(self, source, outfile, interactive=False, runinit=False, format='text', numberify=False, errors=True): + def __init__(self, source, outfile, interactive=False, runinit=False, format='text', numberify=False, errors=True): # noqa: PLR0917 settings = Settings(format=format, numberify=numberify) super().__init__(outfile, interactive, runinit, settings) self.context = beanquery.connect(None) @@ -779,7 +779,7 @@ def print_statistics(entries, options, errors, outfile): @click.option('--no-errors', '-q', is_flag=True, help="Do not report ledger validation errors on load.") @click.version_option('', message=f'beanquery {beanquery.__version__}, beancount {beancount.__version__}') -def main(filename, query, numberify, format, output, no_errors): +def main(filename, query, numberify, format, output, no_errors): # noqa: PLR0917 """An interactive interpreter for the Beancount Query Language. Load Beancount ledger FILENAME and run Beancount Query Language