Skip to content

Commit

Permalink
check db_url just before actual operation is executed (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
yubessy authored Dec 9, 2018
1 parent c02f495 commit a81a607
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
2 changes: 1 addition & 1 deletion sqlcsv/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def _flag_to_bool(spec):


@click.group()
@click.option('-u', '--db-url', envvar='SQLCSV_DB_URL', required=True,
@click.option('-u', '--db-url', envvar='SQLCSV_DB_URL',
help='Datasbase connection URL.')
@click.option('-p', '--pre-sql', default=None,
help='SQL to be run before main operation.')
Expand Down
3 changes: 3 additions & 0 deletions sqlcsv/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ def __init__(self, db_url, pre_sql, post_sql, transaction, header, dialect):

@contextmanager
def _connect_exec(self):
if not self._db_url:
raise ValueError('Database connection URL is not set')

engine = create_engine(self._db_url)

with engine.begin() if self._transaction else engine.connect() as conn:
Expand Down
10 changes: 9 additions & 1 deletion tests/test_command.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from io import StringIO
from unittest.mock import patch

from pytest import fixture
from pytest import fixture, raises
from sqlalchemy import create_engine

import sqlcsv.command
Expand Down Expand Up @@ -63,6 +63,14 @@ def test_connect_exec(db, command_args):
assert result == []


def test_connect_exec_without_db_url(db, command_args):
command_args['db_url'] = None
cmd = sqlcsv.command.Command(**command_args)
with raises(ValueError):
with cmd._connect_exec():
pass


def test_connect_exec_with_transaction(db, command_args):
command_args['transaction'] = True
cmd = sqlcsv.command.Command(**command_args)
Expand Down

0 comments on commit a81a607

Please sign in to comment.