简体   繁体   中英

How do I unittest python method that accesses a database?

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM