2017-08-04 64 views
0

我有下面的代碼,我試圖創建一個測試(工作仍然在進行中):Python的Django的:入門嘲笑

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) 

而且trows這個錯誤

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

查看關於[在哪裏修補]的模擬文檔(https://docs.python.org/3/library/unittest.mock.html#where-to-patch)。請注意,使用threadlocals通常被認爲是一個糟糕的主意,並且在Django代碼中很少需要這樣做。 –

回答

1

我認爲你正在試圖做的具體的事情可以這樣做:

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

但你也應該看看Django testing documentation,如果您還沒有。您可以使用測試客戶端來僞造Web請求。

如果您想嘗試不訪問數據庫的模擬測試,請查看Django Mock Queries。 (我是這個項目的一個小貢獻者。)我也嘗試了嘲笑的觀點,但它很瑣碎。