[英]Feature-testing a REST API with unittest in Django
In our Django project, we have some API views that are defined in urls.py
like this:在我们的 Django 项目中,我们在urls.py
中定义了一些 API 视图,如下所示:
path('api/calendar/calendar_data', calendar_api.serve_data),
and our calendar_api
is an instance of CalendarAPI
, which is instantiated above:我们的calendar_api
是CalendarAPI
一个实例,上面实例化了:
from main.calendar_api import CalendarAPI
from caldav import DAVClient
...
calendar_api = CalendarAPI(client=DAVClient(...))
In the CalendarAPI class we have a method that fetches data from a remote CalDAV calendar using the caldav library like so:在 CalendarAPI 类中,我们有一个方法可以使用 caldav 库从远程 CalDAV 日历中获取数据,如下所示:
class CalendarAPI(ApiEndpoint):
...
def __init__(self, client):
self.caldav_client = client
def _get_event_list(self):
return self.caldav_client.principal().calendars()[0].events()
We wish to mock this method in a way such that _get_event_list returns a predefined array.我们希望以 _get_event_list 返回预定义数组的方式模拟此方法。
Our test case looks like this:我们的测试用例如下所示:
from unittest.mock import patch
from django.test import SimpleTestCase
class TestCalendar(SimpleTestCase):
@patch('main.urls.CalendarAPI')
def test_response_format(self, calendarapi_mock):
calendarapi_mock._get_event_list.return_value = mocked_calendar_events
response = self.client.get('/api/calendar/calendar_data', format='json')
# fails test if response does not match mocked_calendar_events
self._compareResponse(response, mocked_calendar_events)
No matter what we try, we can't get mocking to work.无论我们尝试什么,我们都无法让嘲弄起作用。 If anyone knows of a better way to instantiate classes in urls.py
in light of mocking, please let us know!如果有人知道根据urls.py
在urls.py
中实例化类的更好方法,请告诉我们!
This always gets me as well.这也总是让我着迷。 To mock a method on an instance of CalendarAPI
, you need to mock the method on the return_value
of the mock ( calendarapi_mock.return_value
).要在CalendarAPI
实例上模拟方法,您需要在模拟的return_value
( calendarapi_mock.return_value
) 上模拟该方法。
With calendarapi_mock._get_event_list.return_value
, you're mocking the method on the CalendarAPI
class instead, ie CalendarAPI._get_event_list()
.使用calendarapi_mock._get_event_list.return_value
,您正在模拟CalendarAPI
类上的方法,即CalendarAPI._get_event_list()
。
So instead of所以代替
calendarapi_mock._get_event_list.return_value = mocked_calendar_events
use:用:
calendarapi_mock.return_value._get_event_list.return_value = mocked_calendar_events
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.