Python Django:开始使用模拟器

时间:2017-08-04 20:36:32

标签: python django unit-testing mocking

我有以下代码,我尝试创建测试(仍在进行中):

from core.tests import BaseTestCase                                                                          
from core.views import get_request                                                                           

from entidades.forms import InstituicaoForm                                                                  
from mock import patch                                                                                       


class InstituicaoFormTestCase(BaseTestCase):                                                                 

    def setUp(self):                                                                                         
        super(InstituicaoFormTestCase, self).setUp()                                                         

    @patch('get_request', return_value={'user': 'usuario_qualquer'})                                         
    def test_salva_instituicao_quando_informaram_convenio():                                                    
        import pdb                                                                                              
        pdb.set_trace()                                                                                         
        form = InstituicaoForm()

它失败了,因为当我尝试创建InstituicaoForm时,会调用get_request:

def get_request():
    return getattr(THREAD_LOCAL, 'request', None)

并且它会出现此错误

entidades/tests.py:11: in <module>
    class InstituicaoFormTestCase(BaseTestCase):
entidades/tests.py:16: in InstituicaoFormTestCase
    @patch('get_request', return_value={'user': 'usuario_qualquer'})
.tox/unit/local/lib/python2.7/site-packages/mock/mock.py:1670: in patch
    getter, attribute = _get_target(target)
.tox/unit/local/lib/python2.7/site-packages/mock/mock.py:1522: in _get_target
    (target,))
E   TypeError: Need a valid target to patch. You supplied: 'get_request'
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /home/vinicius/telessaude/.tox/unit/local/lib/python2.7/site-packages/mock/mock.py(1522)_get_target()
-> (target,))

我做错了什么?应该如何模拟这个get_request()方法?

1 个答案:

答案 0 :(得分:1)

我认为您尝试做的具体事情可以这样做:

@patch('core.views.get_request', return_value={'user': 'usuario_qualquer'})

但如果你还没有,你还应该看一下Django testing documentation。您可以使用测试客户端伪造Web请求。

如果您想尝试不访问数据库的模拟测试,请查看Django Mock Queries。 (我是该项目的一个小贡献者。)我也尝试过嘲讽视图,但它很繁琐。