Home > OS >  Mock the result of cursor.execute() when using cx_Oracle for unit testing
Mock the result of cursor.execute() when using cx_Oracle for unit testing

Time:10-18

I am writing unit tests for a python script. I am connecting to oracle DB with cx_Oracle and then running a select query. The script does different things base don whether the query returns any rows or not. My code is something like:

import cx_Oracle
.
.
.
def main():
.
.
.
  connection = cx_Oracle.connect(conn_string)
  cursor = connection.cursor()
  cursor.execute(query)
.
.
.
  headers = [x[0] for x in cursor.description]
  d_file = open(data_file, "w")
        writer = csv.writer(d_file,delimiter='|',lineterminator="\n",quoting=csv.QUOTE_NONE)
        writer.writerow(headers)
        for row in cursor:
            writer.writerow(row)

I would like to patch the cursor.execute() method to return 0 rows. I have tried the following by referring to a couple of answers here on SO. But I am getting the error:

TypeError: Need a valid target to patch. You supplied: 'cx_Oracle'

My test is as follows:

  @mock.patch('cx_Oracle')
  def test_invalid_data(self,mock_cx_Oracle):
    print("Starting test : Test with data file having size < 100000")
    mock_cursor = mock.MagicMock()
    mock_cursor.execute.return_value = []
    mock_cx_Oracle.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor

    with self.assertRaises(SystemExit) as cm:
       dump_intexdb_n_load.main()
    self.assertEqual(cm.exception.code, 1)

How can I mock cursor.execute()?

CodePudding user response:

You need to patch where the object is used, so if your tested module is called dump_intexdb_n_load.py, you should patch dump_intexdb_n_load.cx_Oracle.connect.

See more at https://docs.python.org/3/library/unittest.mock.html#where-to-patch .

  • Related