在python 2.7中使用长链调用模拟静态函数调用

问题描述 投票:0回答:1

我正在尝试测试一个大型遗留Django应用程序,我对Python模拟感到困惑,因为我从未使用过大型Python应用程序。

具体来说,我有一个方法在里面有一个长调用链,生成一个数组:

def update(self): # in some class X
    # ...
    for z in foo.models.Bar.objects.filter(x=1).select('xyz'):
        raise Exception("mocked successfully")

我想嘲笑foo.models.Bar.objects.filter(x=1).select('xyz')

尝试1

我尝试过从各种问题中收集的几种方法,特别是使用装饰器:

@mock.patch('foo.models.Bar.objects.filter.select')
def test_update(self, mock_select):
    mock_select.return_value = [None]
    X().update()

然而,我从未触及模拟调用的内部 - 由于引发异常,测试应该失败。

尝试2

@mock.patch('foo.models.Bar')
def test_update(self, mock_Bar):
    mock_Bar.objects.filter(x=1).select('xyz').return_value = [None]
    X().update()

尝试3

@mock.patch('foo.models.Bar')
def test_update(self, mock_Bar):
    mock_Bar.objects.filter().select().return_value = [None]
    X().update()

尝试4

然后我尝试了一些更基本的东西,看看我是否能得到一个NPE,它也不起作用。

@mock.patch('foo.models.Bar')
def test_update(self, mock_Bar):
    mock_Bar.return_value = None
    X().update()

我的所有尝试都通过了测试,而不是像我期望的那样触发异常。

已经很晚了所以我认为我必须忽略我见过的例子中的一些基本内容!?

python python-2.7 testing mocking
1个回答
1
投票

我能够让它通过嘲弄对象。尝试#3接近,您只需将其更改为filter.return_value.select.return_value即可通过。这是我的建议虽然看起来嘲笑.objects是首选的方式。

@mock.patch('foo.models.Bar.objects')
def test_update(self, mock_bar_objects):
    mock_bar_objects.filter.return_value.select.return_value = [None]
    X().update()

编辑:测试运行输出:

ERROR: test_update (test_x.TestDjango)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/wholevinski/.virtualenvs/p2/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "/home/wholevinski/so_test/django_mock/test/test_x.py", line 10, in test_update
    X().update()
  File "/home/wholevinski/so_test/django_mock/foo/x_module.py", line 6, in update
    raise Exception("mocked successfully")
Exception: mocked successfully

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)
© www.soinside.com 2019 - 2024. All rights reserved.