[英]Using unittest.mock to mock a DRF response
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.我想要做的是模拟对
/core/
URI 的请求,以便它返回模拟响应而不是来自数据库的响应。 For example, considering unit testing in a CI pipeline when the database isn't available.例如,考虑在数据库不可用时在 CI 管道中进行单元测试。
The below is what I have, but print(response.data)
returns the actual response and not the mocked one:以下是我所拥有的,但
print(response.data)
返回实际响应而不是模拟响应:
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?
建议?
@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
.这将模拟视图集的
list
方法,然后您可以将响应 object 作为return_value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.