John Kaff
John Kaff

Reputation: 2075

How can i test django rest framework class based views

I have this code

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def get_data():
        pass

Now i want to test get_data

I want to do something like

view = SnippetList.as_view()
actual = view.get_data()
expected = "test"

But i am not sure how can i make view object

I get this error

*** AttributeError: 'function' object has no attribute 'get_data'

Upvotes: 1

Views: 438

Answers (2)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

You will find this function useful(found 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

You can use it like this:

view = setup_view(
    views.DynamicStorageDownloadView(),
    django.test.RequestFactory().get('/fake-url'),
    path='dummy path')
path = view.get_path()
self.assertEqual(path, 'DUMMY PATH')

Upvotes: 2

Paul
Paul

Reputation: 6737

Looks like as_view() return function, but not an object. Could you please try this code?

view = SnippetList.as_view()(request)

Upvotes: 0

Related Questions