1

库文件

from django.core.urlresolvers import reverse
def render_reverse(f, kwargs):
    """
    kwargs is a dictionary, usually of the form {'args': [cbid]}
    """
    return reverse(f, **kwargs)

测试.py

from lib import render_reverse, print_ls

class LibTest(unittest.TestCase):

def test_render_reverse_is_correct(self):
    #with patch('webclient.apps.codebundles.lib.reverse') as mock_reverse:
    with patch('django.core.urlresolvers.reverse') as mock_reverse:
        from lib import render_reverse
        mock_f = MagicMock(name='f', return_value='dummy_views')
        mock_kwargs = MagicMock(name='kwargs',return_value={'args':['123']})
        mock_reverse.return_value = '/natrium/cb/details/123'
        response = render_reverse(mock_f(), mock_kwargs())

        print mock_reverse.mock_calls  # prints []
    print mock_reverse.mock_calls  # prints []
    self.assertTrue('/natrium/cb/details/' in response)

但相反,我得到

  File "/var/lib/graphyte-webclient/graphyte-webenv/lib/python2.6/site-packages/django/core/urlresolvers.py", line 296, in reverse
    "arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'dummy_readfile' with arguments '('123',)' and keyword arguments '{}' not found.

为什么它调用reverse而不是我的mock_reverse(它正在查找我的 urls.py !!)你可以看到calls返回一个空列表。我什assert mock_reverse.called至它返回错误。

也许我没有提到这个,但是lib只是一堆函数,没有类。

4

2 回答 2

1

两件事情。1. 你需要reverse从 Django 打补丁。2.您需要在上下文管理器中进行导入,以使lib模块导入模拟reverse

from lib import print_ls

class LibTest(unittest.TestCase):

    def test_render_reverse_is_correct(self):
        with patch('django.core.urlresolvers.reverse') as mock_reverse:
            from lib import render_reverse
            mock_f = MagicMock(name='f', return_value='dummy_view')
            mock_kwargs = MagicMock(name='kwargs',return_value={'args':['123']})
            mock_reverse.return_value = '/natrium/cb/details/123'
            response = render_reverse(mock_f, mock_kwargs)

        self.assertTrue('/natrium/cb/details/' in response)
于 2012-04-10T09:47:01.493 回答
0

您没有传递任何关键字参数(这是一个字典),而是传递位置参数(元组)。

此外,您的反向代理方法只传递关键字参数而不是位置参数。

最后,您没有与请求的模式匹配的 URL - 因为您没有传递任何关键字参数,只有位置参数。

于 2012-04-10T09:05:48.533 回答