python - Pytest Django 函数模拟 APITestCase

标签 python django django-rest-framework pytest pytest-django

我正在尝试创建涉及使用 pytest-django 向我的 API 发送 GET 请求的测试,并且我需要在要模拟的 View 中使用一个函数。

我已经尝试过 pytest-mock 和 unittest.mock.patch 中的模拟程序,每次我在某些测试用例中模拟这个函数时,它在其他测试中也仍然被模拟。

第一个.py测试文件:

from unittest.mock import patch
from rest_framework.test import APITestCase
import pytest

@pytest.mark.django_db
class TestFirst(APITestCase):
    @classmethod
    def setUpClass(cls):
        cls.patcher = patch(app.views.function)
        cls.patcher.start()

    @classmethod
    def tearDownClass(cls):
        cls.patcher.stop()

    def test_something(self):
        get_data = self.client.get('/some/url')
        self.assertEqual(200, get_data.status_code)

然后在一些完全不同的 .py 文件中进行测试:

from rest_framework.test import APITestCase
import pytest

@pytest.mark.django_db
class TestSecond(APITestCase):
    def test_something_else(self):
        get_data = self.client.get('/some/url')
        self.assertEqual(200, get_data.status_code)

调试第一个测试用例时,该方法已正确修补。然而,当运行第二个测试时,该方法仍保持修补状态,并且模拟对象保留收到的调用数量。

我错过了什么重要的事情吗?

编辑:我尝试修补定义方法的文件和 View 中的方法名称,但总是得到相同的结果。

EDIT2:值得注意的是,当我更改测试顺序时,第二个测试正确完成,但第一个测试无法修补该方法并调用它未修补,因此失败。

最佳答案

我通过使用 SimpleTestCase 父类(super class)解决了该问题。我仍然不知道为什么会发生这种情况,但似乎不再发生了。

关于python - Pytest Django 函数模拟 APITestCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58783904/

相关文章:

python - Django数据库: sorting by field in latest object in relative database

python - 提交的数据不是文件。检查 DRF 3 中表格上的编码类型

python - 序列化程序被多次调用 django python

django - 对多种用户类型使用 django-rest-auth 注册

python - 如何强制buildout使用已经安装的包

python - 无需 Celery 或 Redis 即可进行进度跟踪的后台任务

python - django 中的正则表达式不匹配

python - 当我将模型实例保存到 MongoDB 数据库中时,为什么 Python 会引发异常?

python - 如何使用 pandas DataFrame 绘图函数为每个子图绘制一个 ylabel

python - 嵌套元组列表的高级排序标准