0
我使用python的“模拟”模块来模拟django项目中的类和函数。 我的项目的结构是:难以嘲笑类使用python“模拟”(Django)
Project name --> 'hello'
App1 ----> hello
App2 ----> hello_world
App3 ----> bye
'你好' 只包含tests.py和settings.py。 '程序hello_world' 包含查看文件'greetings.py'认为是这样的:
from django.shortcuts import render
from django.http import HttpRequest,HttpResponse
from bye import views
# Create your views here.
def greet(request):
views.saybye()
gb_class = views.goodbye()
print gb_class.saygoodbye()
print 'greet called'
return HttpResponse('hello world',content_type='application/html')
'再见' 包含 'views.py' 包含:
from django.shortcuts import render
from django.http import HttpRequest
# Create your views here.
def saybye():
print "goodbye world"
return
class goodbye:
def __init__(self):
print "goodbye's init called"
return
def saygoodbye(self):
return "goodbye.saygoodbye called"
现在,我的'tests.py' 是:
from unittest import TestCase
import mock
from mock import patch
from hello_world import greetings
import bye
from django.test.client import RequestFactory
class TestBasic(TestCase):
def setUp(self):
self.var = 'abc'
self.factory = RequestFactory()
@patch('bye.views.goodbye')
def test_greeting(self,mocksaybye):
assert mocksaybye is bye.views.goodbye
mocksaybye.saygoodbye = mock.MagicMock(return_value="mocked goodbye called")
bye.views.goodbye()
print mocksaybye.saygoodbye()
assert mocksaybye.called
assert mocksaybye.saygoodbye.called
req = self.factory.get('/sayhello/')
greetings.greet(req)
我得到上运行 '蟒蛇manage.py测试' 的输出如下:
mocked goodbye called
goodbye world
<MagicMock name='goodbye().saygoodbye()' id='60566864'>
greet called
我的预期输出的第3行是:"mocked goodbye called"
从我的理解中,mocksaybye类会嘲笑再见类的saygoodbye功能和返回自定义输出嘲笑再见叫。
但是,这不会发生。为什么这样?另外,我应该怎么做才能得到这个期望的输出?
它仍然无法正常工作。结果不受影响。 – pymd 2014-09-11 10:39:27
@nomad,你有没有尝试从答案的第二个解决方案? – stalk 2014-09-11 10:45:35
@nomad,我已经更新了答案 – stalk 2014-09-11 10:50:27