Home > database >  Using unittest.mock to mock a DRF response
Using unittest.mock to mock a DRF response

Time:03-16

My example is pretty basic:

# urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from core import views

router = DefaultRouter()
router.register(r'core', views.CoreViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
# views.py
from rest_framework import mixins, viewsets
from .models import Numbers
from .serializers import NumbersSerializer


class CoreViewSet(viewsets.GenericViewSet,
              mixins.ListModelMixin):
    queryset = Numbers.objects.all()
    serializer_class = NumbersSerializer
# serializers.py
from rest_framework import serializers
from .models import Numbers

class NumbersSerializer(serializers.ModelSerializer):
    class Meta:
        model = Numbers
        fields = '__all__'
# models.py
from django.db import models

# Create your models here.
class Numbers(models.Model):
    odd = models.IntegerField()
    even = models.IntegerField()

    class Meta:
        db_table = 'numbers'

What I'm trying to do is mock the request to the /core/ URI so it returns a mocked response and not the response from the database. For example, considering unit testing in a CI pipeline when the database isn't available.

The below is what I have, but print(response.data) returns the actual response and not the mocked one:

import unittest
from unittest.mock import patch
from rest_framework.test import APIClient

class CoreTestCase(unittest.TestCase):
    
    @patch('core.views')
    def test_response(self, mock_get):
        mock_get.return_value = [{'hello': 'world'}]
        client = APIClient()
        response = client.get('/core/')
        print(response.data)

Not finding the documentation very intuitive in figuring this out, so asking how I should be implementing this. Suggestions?

CodePudding user response:

@patch('core.views')

The above patch just mocks the file, which won't have any effect. What you can use is:

@patch('core.views.CoreViewSet.list') 

This will mock the list method of the viewset, which you can then give a response object as the return_value.

  • Related