python - Pytest Django 函数模拟 APITestCase
问题描述
我正在尝试创建涉及使用 pytest-django 向我的 API 发送 GET 请求的测试,并且我需要在要模拟的视图中使用的函数。
我已经尝试过 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)
在调试第一个测试用例时,该方法已正确修补。但是,在运行第二个测试时,该方法保持修补状态,并且模拟对象保持接收到的调用次数。
我错过了什么重要的东西吗?
编辑:我尝试修补定义方法的文件和视图中的方法名称,但始终保持相同的结果。
EDIT2:值得注意的是,当我更改测试的顺序时,第二个可以正确完成,但第一个无法修补该方法并将其称为未修补,因此失败。
解决方案
我通过使用 SimpleTestCase 超类解决了这个问题。我仍然不知道为什么会发生这种情况,但似乎不再是了。
推荐阅读
- python - 使用beautifulsoup绕过python中的错误520
- javascript - 使用 Javascript 在页面退出时显示弹出模式
- python - 如何正确更新 django 模型?
- python - Pandas Python如何获取除包含总和的行之外的所有其他行的总和
- python - Python NameError:名称“”未定义
- wordpress - 在循环中跳过某些古腾堡块
- apache-spark - Spark Structured Streaming 不会从 Kafka 中提取最后一批
- reactjs - 在 axios 期间更改路由导致 useEffect Hooks 中的内存泄漏
- r - glmnet中的聚合逻辑套索回归
- excel - 在sumproduct公式excel中跳过列