简体   繁体   English

Pytest Django function mocking APITestCase

[英]Pytest Django function mocking APITestCase

I am trying to create tests involving sending GET requests to my API using pytest-django and I need a function used in the views to be mocked.我正在尝试创建涉及使用 pytest-django 向我的 API 发送 GET 请求的测试,并且我需要在要模拟的视图中使用 function。

I have tried mocker from pytest-mock and unittest.mock.patch and every time I mock this function in some test case it remains mocked in the other tests as well.我已经尝试过来自 pytest-mock 和 unittest.mock.patch 的模拟程序,每次我在某些测试用例中模拟这个 function 时,它在其他测试中也会被模拟。

First.py test file: First.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)

and then followed by a test in some completely different.py file:然后在一些完全不同的.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)

When debugging the first test case, the method is patched correctly.在调试第一个测试用例时,该方法已正确修补。 However when running the second test, the method remains patched and the mock object keeps the number of calls received.但是,在运行第二个测试时,该方法仍处于修补状态,并且模拟 object 保持收到的调用数。

Am I missing something important?我错过了什么重要的东西吗?

EDIT: I tried both patching the file where the method is defined and name of the method in views, but always keep getting same result.编辑:我尝试修补定义方法的文件和视图中的方法名称,但始终保持相同的结果。

EDIT2: Worth noting that when I change the order of the tests, the second one completes correctly, but the first one is unable to have the method patched and calls it unpatched, therefore fails. EDIT2:值得注意的是,当我更改测试顺序时,第二个测试正确完成,但第一个无法修补该方法并将其称为未修补,因此失败。

I resolved the issue by using the SimpleTestCase superclass.我通过使用 SimpleTestCase 超类解决了这个问题。 I have still no idea why this was happenning, but doesn't seem to be anymore.我仍然不知道为什么会发生这种情况,但似乎不再是了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM