I am performing unittest on Django command which inserts the data received from API response into a database table. I am using unittest and mock to mock the the Command class and it's method, but I am not sure whether I am doing it correctly or not.
Following is my code for Command and test:
Command
class Command():
def _insert_data(self, report_data, start_date):
for data in report_data:
self.cursor.execute('''
INSERT IGNORE INTO `report`
(
`start_date`, `value_a`, `value_b`, `value_c`,`value_d`,
)
VALUES
(%s,%s,%s,%s,%s);''',
(
str(start_date).split()[0], data['value_a'], data['value_b'], data['value_c'], data['value_d']
)
)
test_report_data.py
from unittest import mock
from base.test import BaseTestCase
from client.models.intergration import Report
from client.management.commands.update_report import Command as ReportCommand
class CommandTestMixin(BaseTestCase):
def setUp(self):
super().setUp()
self.mock_api_response = {
"metrics": {
"value_a": "123",
"value_b": "123",
"value_c": "1.48",
"value_d": "1.0",
}
}
self.mock_row = Report.objects.create(
date = "2022-06-013"
value_a = "123",
value_b = "123" ,
value_c = "1.48",
value_d = "1.0",
)
def mock_response(self, json_data=None):
mock_resp = mock.Mock()
if json_data:
mock_resp.json = mock.Mock(
return_value = json_data
)
return mock_resp
class TestInsertReportData(CommandTestMixin):
def setUp(self):
super().setUp()
def test_api_data_insert(self):
command = ReportCommand()
command._insert_data = mock.Mock()
mock_resp = self.mock_response(json_data = self.mock_api_response)
command._insert_data.return_value = self.mock_row
command._insert_data(mock_resp, "2022-06-13")
row = Report.objects.first()
self.assertEqual(str(row.start_date), "2022-06-13")
self.assertEqual(row.value_a, "123")
self.assertEqual(row.value_b, "123")
self.assertEqual(row.value_c, "1.48")
self.assertEqual(row.value_d, "1.0")
When I run the above test, it runs successfully. But I am not sure if the Test is working how it should be and nothing funky is going on.
I am not sure about return value command._insert_data.return_value = self.mock_row, whether it is right way to do that or not? Because when I pass mock_resp which mocked API response through mocked method _insert_data of Command class I should insert exact same data into the table and in querying the table Report it should return the same value as same as mock_resp.
please correct my test and tell if I am mocking this correctly.