我有这段代码
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def get_data():
pass
现在我要测试get_data
我想做点什么
view = SnippetList.as_view()
actual = view.get_data()
expected = "test"
但我不知道如何制作视图对象
我收到此错误
*** AttributeError: 'function' object has no attribute 'get_data'
答案 0 :(得分:1)
您会发现此功能很有用(找到here):
def setup_view(view, request, *args, **kwargs):
"""Mimic as_view() returned callable, but returns view instance.
args and kwargs are the same you would pass to ``reverse()``
"""
view.request = request
view.args = args
view.kwargs = kwargs
return view
你可以像这样使用它:
view = setup_view(
views.DynamicStorageDownloadView(),
django.test.RequestFactory().get('/fake-url'),
path='dummy path')
path = view.get_path()
self.assertEqual(path, 'DUMMY PATH')
答案 1 :(得分:0)
看起来像as_view()返回函数,但不是对象。 你能试试这个代码吗?
view = SnippetList.as_view()(request)