小编Vah*_*idM的帖子

在类方法中模拟一个函数

我想模拟一个在类方法中调用的函数,同时在Django项目中测试类方法.考虑以下结构:

应用程序/ utils.py

def func():
    ...
    return resp  # outcome is a HTTPResponse object
Run Code Online (Sandbox Code Playgroud)

应用程序/ models.py

from app.utils import func

class MyModel(models.Model):

    # fields

    def call_func(self):
        ...
        func()
        ...
Run Code Online (Sandbox Code Playgroud)

应用程序/测试/ test_my_model.py

from django.test import TestCase
import mock    

from app.models import MyModel

class MyModelTestCase(TestCase):

    fixtures = ['my_model_fixtures.json']

    def setUp(self):
        my_model = MyModel.objects.get(id=1)

    @mock.patch('app.utils.func')
    def fake_mock(self):
        return mock.MagicMock(headers={'content-type': 'text/html'},
                              status_code=2000, 
                              content="Fake 200 Response"))

    def test_my_model(self):
        my_model.call_func()
        ...  # and asserting the parameters returned by func
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,fake_func避免使用mock函数,func而是调用real .我想mock.patch …

python django unit-testing mocking

6
推荐指数
1
解决办法
4015
查看次数

标签 统计

django ×1

mocking ×1

python ×1

unit-testing ×1