i'm quite new to python and mocking generally. So I tried to find a solution to my problem, through reading the documentation: https://docs.python.org/3/library/unittest.mock.html#magic-methods, following article: http://alexmarandon.com/articles/python_mock_gotchas/ and lots of stackoverflow-questions. But I couldn't find a solution yet.
I try to mock two function, which are creating a database connection and put the data into a pandas dataFrame. They are used in the post-function (overwrites the django post-function):
def post(self, request, *args, **kwargs):
db_connection = du_db.get_connection(dbtype='mssql', username=crd.MS_SQL_USER, password=crd.MS_SQL_PWD)
df = du_db.fetch_dataframe(sql, connection=db_connection)
In the testing environment, get_connection
should return nothing and fetch_dataframe
should return a pandas dataframe defined before.
My testing class looks like this:
class IndexViewTest(TestCase):
@mock.patch('du_db.db.get_connection')
@mock.patch('du_db.db.fetch_dataframe')
def setUp(self, mock_get_connection, mock_fetch_dataframe):
self.c = Client()
mock_get_connection = mock_get_connection()
mock_fetch_dataframe = mock_fetch_dataframe()
mock_get_connection.return_value = ""
df = {'lot_of_data': ['xy', 'z'], 'more_data': [8, 9]}
mock_fetch_dataframe.return_value = pd.DataFrame(df)
assert mock_get_connection is data_utils.db.get_connection()
assert mock_fetch_dataframe is data_utils.db.fetch_dataframe()
assert mock_get_connection.called
assert mock_get_connection.called
# Lot of test-functions similar to this:
def test_valid_data(self):
resp = self.c.post('/', data={'id': 3338})
self.assertEqual(resp.status_code, 200)
self.assertContains(resp, 'Hello', status_code=200)
I get the following error-message:
The replacing of the original functions through the mocks doesn't seam to work.
Thanks for your help.