【问题标题】:Python Django: getting started with mocksPython Django:开始使用模拟
【发布时间】:2017-08-04 20:36:32
【问题描述】:

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

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() 方法?

【问题讨论】:

  • where to patch 上查看模拟文档。请注意,使用 threadlocals 通常被认为是一个坏主意,在 Django 代码中很少需要这样做。

标签: python django unit-testing mocking


【解决方案1】:

我认为你想要做的具体事情可以这样完成:

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

但您也应该查看Django testing documentation,如果您还没有的话。您可以使用测试客户端来伪造 Web 请求。

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

【讨论】:

  • 救了我的命!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
相关资源
最近更新 更多