难以使用python模拟类';模拟';(django)
我正在使用python的“mock”模块来模拟django项目中的类和函数。 我的项目结构如下:难以使用python模拟类';模拟';(django),python,django,unit-testing,mocking,patch,Python,Django,Unit Testing,Mocking,Patch,我正在使用python的“mock”模块来模拟django项目中的类和函数。 我的项目结构如下: Project name --> 'hello' App1 ----> hello App2 ----> hello_world App3 ----> bye “hello”只包含tests.py和settings.pyhello_world'包含视图文件'hellives.py',如
Project name --> 'hello'
App1 ----> hello
App2 ----> hello_world
App3 ----> bye
“hello”只包含tests.py和settings.pyhello_world'包含视图文件'hellives.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')
“bye”包含“视图.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)
我在运行“python manage.py test”时得到以下输出:
mocked goodbye called
goodbye world
<MagicMock name='goodbye().saygoodbye()' id='60566864'>
greet called
模拟再见呼叫
再见世界
打电话问候
我希望输出的第三行是:“mocked bye called”
,据我所知,mocksaybeye类将模拟bye类的saybeye函数,并返回自定义输出mocked bye called
然而,这并没有发生。为什么会这样?另外,我应该怎么做才能获得所需的输出?您需要使用方法,而不是。而不是
因此,与此代码不同:
@patch('bye.views.goodbye')
def test_greeting(self,mocksaybye):
# ...
mocksaybye.saygoodbye = mock.MagicMock(return_value="mocked goodbye called")
# ...
使用此(未测试):
@nomad,你试过答案中的第二个解决方案了吗?这个答案实际上与
返回值
相同。我认为问题在于您需要模拟问候语。视图。再见
。还有可能的问题:再见
是一个旧式类,它不是从对象继承的
@simeonviser仍然不起作用。输出仍然相同,但上述解决方案均无效。输出不受影响。
@patch.object('bye.views.goodbye', 'saygoodbye')
def test_greeting(self,mocksaybye):
# ...
mocksaybye.side_effect = lambda: "mocked goodbye called"
# ...