Reputation: 47
def insert_env(self, env):
"""Inserts a new environment into ENV_TABLE
Keyword arguments:
env -- name of environment to be inserted
"""
info = {}
# populate info dictionary
sql = (
"""INSERT INTO my_table (...) VALUES (...)""")
try:
DML(sql, info)
except oracleException as e:
logger.debug('dml {0} resulted in error {1}'.format(sql, e))
Here I have a function that populations an info
dictionary and inserts the values into a table in a database. DML
is a helper method from another function that has been there for a while now and makes the call to the oracle database, with most of the database info already hardcoded in that function. How can I unittest this function? I can't mock a database because the helper function is hardcoded to access our production db.
Upvotes: 0
Views: 1607
Reputation: 1884
First make your sql string a global constant preferably in a second file. Then mock the db calls.
# Need to test exception scenario
class oracleExceptionStub(oracleException):
# bypass constructor
def __init__(self):
pass
class Test...(unittest.Testcase):
@mock.patch('path_to_DML')
def test_insert_valid(self, mock_dml):
test_env = ...
expected_info = ...
insert_env(test_env)
mock_dml.assert_called_once_with(sql_contant, expected_info)
@mock.patch('logger.debug')
@mock.patch('path_to_DML', side_effect=oracleExceptionStub)
def test_insert_invalid(self, mock_dml, mock_logger):
insert_env(..., ...)
self.assertTrue(mock_logger.called)
Upvotes: 1
Reputation: 532238
The help function DML
is not part of the unit you are testing; mock it. The only thing you need to test in insert_env
, apparently, is that DML
is called with the appropriate arguments, and that the logger is used if DML
raises an exception.
The fact that info
, a local variable in insert_env
, is never used again after DML
is called suggests that this is not the full function. There may be more to test, but it is impossible to say with the information given.
Upvotes: 1