测试时如何在Django Rest Framework端点内模拟第三方库? [英] How do I mock a third party library inside a Django Rest Framework endpoint while testing?

查看:59
本文介绍了测试时如何在Django Rest Framework端点内模拟第三方库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中的用户创建端点会创建一个与我的Django用户具有相同ID的Firebase用户(我的应用程序中有一个聊天室,由firebase驱动).

The user creation endpoint in my app creates a firebase user (I have a chat room inside the app, powered by firebase) with the same id as my django user.

from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework import permissions
from apps.core.services import firebase_chat

class UserCreate(generics.GenericAPIView):

    permission_classes = [permissions.AllowAny]

    @transaction.atomic
    def put(self, request):
        user = User.objects.create(**request.data)
        firebase_chat.create_user(user)

firebase_chat是我围绕标准firebase库创建的包装.

firebase_chat is a wrapper I created around the standard firebase library.

我正在按照DRF指南中的建议编写测试:

I'm writing my tests like recommended in DRF's guide:

from django.urls import reverse
from django.test import TestCase
from rest_framework.test import APIClient

class UserCreateTest(TestCase):

    def test_user_create__all_valid__user_created(self):
        client = APIClient()
        client.force_authenticate(user=User.objects.create(username='test'))
        response = client.put(reverse('user-create'))
        self.assertTrue(response.data['something'])

但是,这导致在Firebase中创建实际用户.这不仅使测试失败(firebase库引发异常),而且还命中了实际的firebase服务器,并用测试数据填充了该服务器.

However, this leads to creating an actual user in Firebase. Not only this fails the test (the firebase library throws an exception), it also hits the actual firebase server, filling it with test data.

在测试过程中如何模拟或禁用Firebase库?

推荐答案

模拟视图使用的 firebase_chat 导入应该很简单.一种方法是使用 unittest.mock 中的 patch 装饰器.

It should be straightforward to mock out the firebase_chat import used by your view. One way of doing that is to use the patch decorator from unittest.mock.

from django.urls import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from unittest.mock import patch


class UserCreateTest(TestCase):

    @patch('your.app.view.firebase_chat')
    def test_user_create__all_valid__user_created(self, mock_firebase_chat):
        client = APIClient()
        client.force_authenticate(user=User.objects.create(username='test'))
        response = client.put(reverse('user-create'))
        self.assertTrue(response.data['something'])
        # Assert that `create_user` was called
        mock_firebase_chat.create_user.assert_called()

如果您使用的是Python 2,则需要 pip install模拟,因为它未与 unittest 捆绑在一起.

If you're using Python 2, you will need to pip install mock as it is not bundled with unittest.

这篇关于测试时如何在Django Rest Framework端点内模拟第三方库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆