My example is pretty basic:
JavaScript
x
12
12
1
# urls.py
2
from django.urls import include, path
3
from rest_framework.routers import DefaultRouter
4
from core import views
5
6
router = DefaultRouter()
7
router.register(r'core', views.CoreViewSet)
8
9
urlpatterns = [
10
path('', include(router.urls)),
11
]
12
JavaScript
1
11
11
1
# views.py
2
from rest_framework import mixins, viewsets
3
from .models import Numbers
4
from .serializers import NumbersSerializer
5
6
7
class CoreViewSet(viewsets.GenericViewSet,
8
mixins.ListModelMixin):
9
queryset = Numbers.objects.all()
10
serializer_class = NumbersSerializer
11
JavaScript
1
9
1
# serializers.py
2
from rest_framework import serializers
3
from .models import Numbers
4
5
class NumbersSerializer(serializers.ModelSerializer):
6
class Meta:
7
model = Numbers
8
fields = '__all__'
9
JavaScript
1
11
11
1
# models.py
2
from django.db import models
3
4
# Create your models here.
5
class Numbers(models.Model):
6
odd = models.IntegerField()
7
even = models.IntegerField()
8
9
class Meta:
10
db_table = 'numbers'
11
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:
JavaScript
1
13
13
1
import unittest
2
from unittest.mock import patch
3
from rest_framework.test import APIClient
4
5
class CoreTestCase(unittest.TestCase):
6
7
@patch('core.views')
8
def test_response(self, mock_get):
9
mock_get.return_value = [{'hello': 'world'}]
10
client = APIClient()
11
response = client.get('/core/')
12
print(response.data)
13
Not finding the documentation very intuitive in figuring this out, so asking how I should be implementing this. Suggestions?
Advertisement
Answer
JavaScript
1
2
1
@patch('core.views')
2
The above patch just mocks the file, which won’t have any effect. What you can use is:
JavaScript
1
2
1
@patch('core.views.CoreViewSet.list')
2
This will mock the list
method of the viewset, which you can then give a response object as the return_value
.