我正在尝试创建涉及使用 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/