How to unit test Django’s Function Based Views

Let’s assume than the URL pattern to your Function Based View is defined like that:
urls.py

urlpatterns = patterns(
    ...,
    url(r'^$', views.index, name='index'),
    ...
)

and your function based view looks like this:
views.py

@api_view(['GET'])
@permission_classes((AllowAny,))
def index(request):
    data = {
        'field': 'value'
    }
    return Response(data)

Then you can unit test such view by creating a minimal instance
of the HttpRequest and pass it to that view.
I tried to mock to test such view with the Mock library, by with no luck!!!
If case you know how to do it with Mock, then let me know!

def test_index_function_based_view():
    _request = HttpRequest()
    _request.method = 'GET'
    request = Request(_request)
    response = index(request)
    assert response.data['field'] ==  'value'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s