0

I am new in Python. I am trying to write a UT using MagicMock as follows:

    db_obj = MagicMock(DBFactory.get_db_for_env)
    db_obj.fetch_cursor_records.return_value = self.get_success_csv()

    db_obj.fetch_cursor_records.assert_called_once_with()
    upload_to_s3.assert_called_once_with(json.dumps(self.get_success_csv()))

    @staticmethod
    def get_success_csv():
       return [{"test_col1": "test_val1", "test_col2" : "test_val2"}]

Here I am facing the error as follows:

AttributeError: Mock object has no attribute 'fetch_cursor_records'

Even while I am mocking fetch_cursor_records as follows:

self.extractor.db_obj.fetch_cursor_records = 
MagicMock(DBFactory.get_db_for_env.fetch_cursor_records)

I am still facing the issue as follows:

AttributeError: 'function' object has no attribute 'fetch_cursor_records'

EDIT :

I could solve the above issue with answer I have posted. But it seems to be working with Python 3.7. But as per requirement, I had to test the same with python 3.6. Then it started failing.

Though I created mock with @patch(DBFactory.get_db_for_env), but the get_db_for_env() function of DBFactory class actually gets called while running unit test with python 3.6. I have not any clue regarding how to fix the same.

Joy
  • 4,197
  • 14
  • 61
  • 131

1 Answers1

0

I have been able to solve it following way:

@patch('DBFactory.get_db_for_env')
def test_extract_success(self, mock_db_obj):
    mock_db_obj.fetch_cursor_records.return_value = self.get_success_csv()
    self.db_obj = mock_db_obj
    self.call_function()
    self.db_obj.fetch_cursor_records.assert_called_once_with()
Joy
  • 4,197
  • 14
  • 61
  • 131