【发布时间】:2015-06-10 02:04:36
【问题描述】:
我想模拟一个在 Django 项目中测试类方法时在类方法中调用的函数。考虑以下结构:
app/utils.py
def func():
...
return resp # outcome is a HTTPResponse object
app/models.py
from app.utils import func
class MyModel(models.Model):
# fields
def call_func(self):
...
func()
...
app/tests/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_func(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
当我运行测试时,模拟函数fake_func() 被避免,而是调用真正的func()。我猜mock.patch 装饰器中的范围可能是错误的,但我找不到让它工作的方法。我该怎么办?
【问题讨论】:
标签: python django unit-testing mocking